Enum
Enumeration
A type that defines a set of named constants. Improves code readability and safety.
Enumeration
A type that defines a set of named constants. Improves code readability and safety.
An Enum (Enumeration) is a programming construct that defines a set of related constants as a single type. It was first introduced in the Pascal language in the 1970s, and today it is supported by most modern programming languages, including Java, C#, TypeScript, Python, and Rust.
The core purpose of an Enum is to improve code readability by using meaningful names instead of magic numbers or string literals. For example, using clear names such as Status.PENDING, Status.APPROVED, and Status.REJECTED instead of the status codes 0, 1, and 2 makes the intent of the code clear at a glance.
Because an Enum is type-checked at compile time, it prevents invalid values from being introduced in advance. IDE autocompletion can also be used, which improves development productivity, and reference locations can be easily traced during refactoring.
In practice, Enums are used wherever there is a fixed set of choices, such as status (Status), role (Role), permission (Permission), direction (Direction), and day of the week (DayOfWeek). In particular, using an Enum instead of a string for API response codes, database status fields, configuration options, and the like can eliminate typo-related bugs at the source.
// 1. TypeScript - 숫자형 Enum
enum OrderStatus {
PENDING = 0, // 대기중
CONFIRMED = 1, // 확인됨
SHIPPED = 2, // 배송중
DELIVERED = 3, // 배송완료
CANCELLED = 4 // 취소됨
}
// 2. TypeScript - 문자열 Enum (권장)
enum UserRole {
ADMIN = 'ADMIN',
MANAGER = 'MANAGER',
USER = 'USER',
GUEST = 'GUEST'
}
// 3. Enum 사용 예시
interface User {
id: number;
name: string;
role: UserRole;
}
function checkPermission(user: User): boolean {
// switch문과 함께 사용하면 모든 케이스 처리 보장
switch (user.role) {
case UserRole.ADMIN:
return true;
case UserRole.MANAGER:
return true;
case UserRole.USER:
return false;
case UserRole.GUEST:
return false;
default:
// 새 역할 추가 시 컴파일 에러로 누락 방지
const _exhaustive: never = user.role;
return false;
}
}
// 4. Python Enum 예시
// from enum import Enum, auto
//
// class Color(Enum):
// RED = auto() # 1
// GREEN = auto() # 2
// BLUE = auto() # 3
//
// def get_hex_code(color: Color) -> str:
// mapping = {
// Color.RED: '#FF0000',
// Color.GREEN: '#00FF00',
// Color.BLUE: '#0000FF'
// }
// return mapping[color]
// 5. 실제 API 응답에서의 활용
const order = {
id: 12345,
status: OrderStatus.SHIPPED,
createdAt: new Date()
};
console.log(`주문 상태: ${OrderStatus[order.status]}`); // "주문 상태: SHIPPED"
console.log(`상태 코드: ${order.status}`); // "상태 코드: 2"
"We manage payment status as strings, so typo bugs happen often. If we refactor to a PaymentStatus Enum, we get type safety and can also use IDE autocompletion."
"Using an Enum lets you catch invalid values at compile time, which reduces runtime errors. In TypeScript, string Enums are recommended because you can check values directly when debugging and there is no reverse mapping issue."
"Please change status === 'pending' to status === OrderStatus.PENDING here. A string literal doesn't produce an error even if there's a typo, but with an Enum, entering a wrong value immediately causes a compile error, so it's safe."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
A TypeScript numeric Enum generates a reverse mapping from values to names, so the results of Object.keys() or Object.values() may differ from what you expect. Use a string Enum or use const enum.
If you have stored numeric Enum values in a database, changing the order of the Enum changes the meaning of the existing data. Use a string Enum or specify the values explicitly.
In TypeScript, using const enum causes it to be replaced inline at compile time, so there is no runtime overhead. However, caution is needed with the isolatedModules option or in declaration files.