[230609] TypeScript 공식문서 (Everyday types)

1. TypeScript 복습

  • 이전에 했던 내용 정독

2. TypeScript Everyday types 정독 완료

Literal Types

  • 구체적인 값을 타입 위치에서 지정 가능
const c: "HELLO" = "HELLO";
let l: string = "HELLO";
  • const 는 변경이 불가능하기 때문에 리터럴 타입으로 추론된다.
//let 을 사용하면 string 으로 들어감
let a = "UP";
test(a); // ERROR
test(a as "UP"); // NO ERROR
function test(direction: "UP" | "DOWN") {}
  • boolean 은 애초에 true false 인 리터럴 union 의 type alias 이다.
let a: boolean = false;
test(a); // NO ERROR
function test(direction: true | false) {}

리터럴 추론

  • const 객체는 프로퍼티까지 const 아님
  • const 객체의 모든 프로퍼티를 const로 하기 위해서는 as const 구문이 필요합니다.
const obj = { x: 1 } as const;
obj.x = 2; // ERROR
  • 상수는 리터럴타입으로 추론되고, 상수가 아닌 경우에는 typescript는 그 이후 값이 변화할 수 있다고 가정합니다.
function handleRequest(req: { method: "GET" | "POST" }) {
  // TBD
}

handleRequest({ method: "GET" });

const req = { method: "GET" };
handleRequest(req); // ERROR

const req2 = { method: "GET" } as const;
handleRequest(req2); // NO ERROR

const req3 = { method: "GET" as const };
handleRequest(req3); // NO ERROR
let a: boolean = false;
test(a); // NO ERROR
function test(direction: true | false) {}

null , undefined

  • null 은 변수에 값이 의도적으로 없음을 나타내는 특별한 값
  • nudefined 는 변수가 아무런 값도 할당 받지 않았을 때의 기본 값

Enums

  • 상수의 집함
enum Direction {
  Up,
  Down,
  Left,
  Right,
}

Categories:

Updated:

Leave a comment