Course contentsShow
← TypeScript
Lesson 524 of 1,79612. EnumsFree lesson

Choosing Between Enums and Unions

Practical decision framework: use unions by default, enums when runtime iteration is essential.

Choosing Between Enums and Unions

You'll learn: A practical framework for deciding when to use enums versus string-literal unions in real codebases.

The Default Choice: Start with Unions

After weighing all the trade-offs you've learned—bundle size, tree-shaking, type safety, refactoring, and runtime behavior—here's the pragmatic rule of thumb: use string-literal unions by default.

Unions give you compile-time type safety with zero runtime code. They tree-shake automatically. They interoperate seamlessly with JavaScript libraries. For most everyday use cases—action types, status codes, color names—they're the lighter, simpler choice.

// Default choice: union
type Status = "pending" | "success" | "error";

function updateStatus(status: Status) {
  // Type-safe, no runtime overhead
}

When Enums Earn Their Place

Switch to an enum when you need runtime iteration or reflection. If your code must loop over all possible values, display them in a UI, validate user input dynamically, or map over members at runtime, enums provide that capability out of the box:

enum Permission {
  Read = "READ",
  Write = "WRITE",
  Delete = "DELETE"
}

// Generate UI checkboxes from all permissions
Object.values(Permission).forEach(perm => {
  createCheckbox(perm); // This requires runtime access
});

You can't iterate over a union's members at runtime—they don't exist as values.

The Decision Framework

  • Can you list values at compile-time only? → Union
  • Need to iterate/validate at runtime? → Enum
  • Shipping to npm? → Union (better interop)
  • Internal app with reflection needs? → Enum

Key Takeaway: Default to string-literal unions for their simplicity and zero overhead; use enums only when runtime iteration or reflection is essential to your application logic.