참고 자료
"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이라고 할 수 있다.
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에 대한 상수를 열거하여 사용할 수 있음을 알 수 있다.
const
를 사용하게 되는데, color code나 위와 같은 response code처럼 확연히 정해져있는 상수를 사용할 때, 상수명이 더욱 직관적이라 코드의 문맥을 알기 쉽다.const
로만 사용한다고 상상해보자. 그리고 이를 협업한다고 상상해보자.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
로 충분히 열거할 수 있는 상수라면 이를 사용하는 것이 더 나은 코드라고 말한다.