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

  1. Define a numeric enum: enum Direction { Up, Down, Left, Right }
  2. Define a string enum: enum Direction { Up = 'UP', Down = 'DOWN' }
  3. Use const enums for compile-time inlining: const enum Status { Active = 1 }
  4. Access values: const dir = Direction.Up;
  5. 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.