[TypeScript] Enums에 대하여

어쩌다·2023년 2월 16일
0

참고 자료

Typescript Documentation


Enums에 대한 정의

"Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums."

  • Typescript documentaion

이를 간단하게 번역하자면 개발자가 명명한 상수에 대한 집합이다.
Enums을 열거형 타입이라고 하는 것처럼, 상수에 대한 variable를 열거할 수 있는 type이라고 할 수 있다.

try it

enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}

enum이란 키워드를 사용하여 선언하고, object 형식인 것을 알 수 있다.


enum UserResponse {
  No = 0,
  Yes = 1,
}

function respond(recipient: string, message: UserResponse): void {
  // ...
}

respond("Princess Caroline", UserResponse.Yes);

이런 식으로, CRUD 로직을 구현할 때 front에 던져줄 수 있는 code는 보통 상수에 해당한다.
따라서 enum을 통해 response message에 대한 상수를 열거하여 사용할 수 있음을 알 수 있다.


enum을 왜 사용해야 하는가?

  1. 직관적이다.
    보통 상수를 선언할 때 const를 사용하게 되는데, color code나 위와 같은 response code처럼 확연히 정해져있는 상수를 사용할 때, 상수명이 더욱 직관적이라 코드의 문맥을 알기 쉽다.
  2. 강제성이 있다.
    모든 상수를 const로만 사용한다고 상상해보자. 그리고 이를 협업한다고 상상해보자.
    규칙이란 것이 있어도 중구난방이 될 수 있는 가능성은 난무하다.
    하지만 이러한 상수들을 enum을 통해 이렇게 쓸 수밖에 없도록 만들게 되면 variable은 더욱 확고해질 것이다.

Enums VS Object

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

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

EDirection.Up;

ODirection.Up;

// Using the enum as a parameter
function walk(dir: EDirection) {}

// It requires an extra line to pull out the values
type Direction = typeof ODirection[keyof typeof ODirection];
function run(dir: Direction) {}

walk(EDirection.Left);
run(ODirection.Right);

Typescript documentation에 따르면, 모던 typescript에선 const로 충분히 열거할 수 있는 상수라면 이를 사용하는 것이 더 나은 코드라고 말한다.

profile
혼자 공부하는 공간

0개의 댓글