거꾸로 바라본 세상
반응형

1.타입시스템

타입스크립트는 자바스크립트의 7가지 원시타입과 동일

  • null; //null
  • undefined; //undefined
  • boolean; //true or false
  • string; //”Hello”
  • number; //1233
  • bigint; //1233n
  • symbol; //Symbol(”Hello”)

타입 시스템은 프로그램에서 가질 수 있는 타입을 이해하는 방법에 대한 규칙

  1. 코드를 읽고 존재하는 모든 타입과 값을 이해
  2. 각 값이 초기선언에서 가질 수 있는 타입을 확인
  3. 각 값이 추후 코드에서 어떻게 사용될 수 있는지 모든 방법을 확인
  4. 값의 사용법이 타입과 일치하지 않으면 사용자에게 오류를 표시

타입스크립트 타입 오류 종류

  • 구문 오류 : 타입스크립트가 자바스크립트로 변환되는 것을 차단한 경우
let let wat;
//      ~~~
/Error: ',' expected.
  • 타입 오류 : 타입 검사기에 따라 프로그램 타입에서 일치하지 않는 것이 감지된 경우
console.logs('Hello world');
//Property 'logs' does not exist on type 'Console'. Did you mean 'log'?

타입 애너테이이션

초기값을 할당하지 않고 변수의 타입을 선언할 수 있는 구문인 타입 애너테이션을 제공한다. 변수의 이름 뒤에 배치되며 콜론(:)과 타입을 차례로 기재

let singer; //any 

singer = "Ella Fitzgerald"; //type: string

singer.toUpperCase();

singer = 19; //type: number
singer.toPrecision(1);

singer.toUpperCase();
//Property 'toUpperCase' does not exist on type 'number'.

타입 애너테이션을 지정 후 숫자를 대입 하면 타입 오류가 발생되는 것을 확인

let singer: string;
singer = 'Ella';
singer = 19;
//Type 'number' is not assignable to type 'string'.

2.유니언과 리터럴

유니언(Union) : 값에 허용된 타입을 두 개 이상 가능한 타입으로 확장하는 것

let mathematician = Math.random() > 0.5 ? undefined : "Mark Goldberg";
//let mathematician: string | undefined

//유니언 타입 선언
let thinker: string | null = null;

if (Math.random() > 0.5) {
    thinker = "Susanne Langer";

mathematician은 undefined거나 string 타입으로 ‘이것 혹은 저것’ 과 같이 정확히 어떤 타입인지는 모르지만 두 개 이상의 옵션 중하나라는 것을 표현하는 것이 유니언 이라고한다.

내로잉(Narrowing) : 값에 허용된 타입이 하나 이상의 가능한 타입이 되지 않도록 좁히는 것

  • 값 할당을 통한 내로잉
let admiral: number | string;

admiral = 'Grace Hopper';
admiral.toUpperCase();

admiral.toFixed();
//Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?

let inventor: number | string ='Hedy Lamarr';

inventor.toUpperCase();

inventor.toFixed();
//Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?
  • 조건검사를 통한 내로잉
//let scientist: number: string
let scientist = Math.random() > 0.5 ? "Rosalind Franklin" : 51;

if (scientist === 'Rosalind Franklin') {
    scientist.toUpperCase();
}

scientist.toUpperCase();
//Property 'toUpperCase' does not exist on type 'string | number'.
//  Property 'toUpperCase' does not exist on type 'number'.
  • typeof검사를 통한 내로잉
let researcher = Math.random() > 0.5 ? "Ros" : 51;

if (typeof researcher === 'string') {
    researcher.toUpperCase();
} else {
    researcher.toFixed();
}

typeof researcher === "string" ? researcher.toUpperCase() : researcher.toFixed();

리터럴(literal) 좀 더 구체적인 버전의 특정 원시 타입 값

const philosopher = 'Hypatia';

객체 타입 선언

//객체 타입 선언
let poet: {
    born: number;
    name: string;
};
poet = {
    born:1000,
    name: 'Hello'
}

별칭 객체 타입

type poet1 = {
    born: number;
    name: string;
}
let poetLater: poet1;

poetLater = {
    born: 1935,
    name: "Sara Teasdale",
};

구조적 타이핑

type WithFirstName = {
    firstName: string;
}
type WithLastName = {
    lastName: string;
}
const hasBoth = {
    firstName: "Lucille",
    lastName: "Clifton"
}
let withFirstName: WithFirstName = hasBoth;
let withLastName: WithLastName = hasBoth;

변수명 뒤 ? 가 붙을경우 ‘start?’ HasStartTime에서 start를 생략가능.

type TimeRange = {
    start?: Date;
}
const HasStartTime: TimeRange = {
    
}
반응형

'Language > TypeScript' 카테고리의 다른 글

[TypeScript] 인터페이스  (0) 2023.08.07
[TypeScript] 함수, 배열  (0) 2023.08.07
profile

거꾸로 바라본 세상

@란지에。

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!