TypeScript, 열거 타입은 열거형보다 객체 방식이 보다 권장됨

열거 타입을 정의하기 위해 TypeScript는 열거형을 제공합니다. 예를들어 다음 코드가 가능합니다.

const enum EDirection {
  Up,
  Down,
  Left,
  Right,
}

function walk(dir: EDirection) {}
walk(EDirection.Left);

위의 코드와 비슷한 맥락으로, 이번에는 열거형을 사용하지 않고 객체 방식으로 작성하면 다음과 같습니다.

const ODirection = {
  Up: 0,
  Down: 1,
  Left: 2,
  Right: 3,
} as const;

type Direction = typeof ODirection[keyof typeof ODirection];
function run(dir: Direction) {}
run(ODirection.Right);

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다