How to use enums in TypeScript
· Category: TypeScript
Short answer
Enums define a set of named constants. TypeScript supports numeric enums, string enums, and const enums for zero-overhead abstractions.
Steps
- Define a numeric enum:
enum Direction { Up, Down, Left, Right } - Define a string enum:
enum Direction { Up = 'UP', Down = 'DOWN' } - Use const enums for compile-time inlining:
const enum Status { Active = 1 } - Access values:
const dir = Direction.Up; - Use enums in type positions:
function move(dir: Direction) { ... }
Tips
- String enums are safer because they do not rely on reverse mapping and behave more predictably.
- Consider using union types (
type Status = 'active' | 'inactive') instead of enums for smaller sets to avoid runtime objects.
Common issues
- Numeric enums generate reverse mappings in JavaScript, which can be surprising.
- Const enums disappear at runtime, so you cannot reference them dynamically.