본문 바로가기
Language/TypeScript

enum, keyof, typeof

by Zayne 2023. 2. 7.

■ 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", b: "2", c: "3" } as const; // as const 없으면 obj 타입은 string으로 추론
type thisKey = keyof typeof obj; // "a" | "b" | "c"
type thisValue = typeof obj[keyof typeof obj] // "1" | "2" | "3"