Enums define named constants that can be numeric or string values. They exist at runtime as objects. Union types ('a' | 'b') are often preferred for string literals as they're lighter weight and better tree-shaken. Use enums when you need runtime access to values.
Enum Types:
Enums vs Union Types:
Enums:
Union Types:
Recommendation:
// Numeric enum - auto-incrementing from 0
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
// Custom starting value
enum HttpStatus {
Ok = 200,
Created = 201,
BadRequest = 400,
NotFound = 404
}
// String enum - must initialize all members
enum Color {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE'
}
// Using enums
function move(direction: Direction) {
console.log(Direction[direction]); // Reverse mapping (numeric only)
}
move(Direction.Up); // Logs: 'Up'
move(Direction.Left); // Logs: 'Left'
// Enum exists at runtime
console.log(Direction); // { '0': 'Up', '1': 'Down', ... Up: 0, Down: 1, ... }