본문 바로가기

Language/TypeScript18

union(|)과 intersection(&) ■ type 과 interface type A = { a: string }; const a: A = { a: "hello" }; // 상속 및 구현이 필요할 경우 interface 사용 interface B { a: string; } const b: B = { a: "hello" }; ■ union(|) type A = string | number; const a: A = 5; const b: A = "hello"; ■ intersection(&) type A = { hello: "world" } & { zayne: "lee" }; const a: A = { hello: "world", zayne: "lee" }; 2023. 2. 9.
enum, keyof, typeof ■ enum const enum EDirection { Up, // 위에서부터 0,1,2,3... 의 값을 가진다. Down, // Down = 'hello' 등의 문자열을 값으로 지정해줄 수도 있다. Left, Right, } const a = EDirection.Up; // a = 0 const b = EDirection.Left; // b = 2 // 위 enum 정의와 같은 표현 const ODirection = { Up: 0, Down: 1, Left: 2, Right: 3, } as const; // 위 값을 상수로 쓰겠다는 표현. readonly로 값 수정 불가 const d = ODirection.Up; // d = 0 ■ keyof , typeof const obj = { a: "1", .. 2023. 2. 7.
원시 래퍼 타입, 템플릿 리터럴 타입, rest, 튜플 ■ 원시 래퍼 타입 const a: string = "hello"; const b: String = "hello"; // 대문자 String은 래퍼 타입으로 사용 X ■ 템플릿 리터럴 타입 type World = "world" | "hell"; type Greeting = `hello ${World}`; const a: Greeting = "hello hell"; const b: Greeting = "hello world"; ■ rest let arr: string[] = []; let arr2: Array = []; function rest(a: string, ...args: string[]) { console.log(a, ...args); // 1, [ 2 , 3 ] } rest("1", "2", ".. 2023. 2. 5.
never 타입과 느낌표 ■ never 타입 try { const array = []; // noImplicitAny가 false일 때 array[0]; } catch(error) { error; } 타입스크립트에서는 빈배열의 경우 never[] 타입이 할당된다. (never 좋은 설명 글) ■ 느낌표 const head = document.querySelector('#head')!; console.log(head); const head = document.querySelector('#head'); if (head) { console.log(head); } null 이 존재할 수 있는 값에 느낌표(!)를 붙이면 null 타입이 사라진다. 느낌표(!)는 값이 항상 있음을 개발자가 보증하는 것이므로 위험 느낌표(!) 대신 if 문으.. 2023. 2. 4.