JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
Prev
typescript
mid
enums

What are enums in TypeScript and when should you use them vs union types?

enums
unions
const-enum
string-literals
runtime
Quick Answer

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.

Detailed Explanation

Enum Types:

  • Numeric enums: Auto-incrementing numbers
  • String enums: Explicit string values
  • Const enums: Inlined at compile time
  • Heterogeneous: Mixed (not recommended)

Enums vs Union Types:

Enums:

  • Exist at runtime as objects
  • Can iterate over values
  • Reverse mapping (numeric only)
  • Heavier bundle impact

Union Types:

  • Erased at compile time
  • Lighter weight
  • Better tree shaking
  • No runtime overhead

Recommendation:

  • Prefer union types for string literals
  • Use enums when runtime object needed
  • Use const enums for zero runtime cost

Code Examples

Numeric and string enums
// 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, ... }

Resources

TypeScript - Enums

docs

Related Questions

What are union and intersection types in TypeScript?

junior
unions

What are TypeScript's built-in utility types and when do you use them?

mid
utility-types
Previous
How do TypeScript modules work and what's the difference between import types?