TypeScript Developer interview question · Most asked

Should you use enums or union types in TypeScript?

Summary

Many teams prefer string literal unions (optionally derived from an as const object) over enums: unions are erased at compile time, work with structural typing and plain strings, and are supported by type-stripping tools. Enums generate runtime objects and have quirks (numeric enums accept any number in older versions; const enum breaks with isolated modules).

Longer Answer

Enums are still fine for some codebases, especially string enums with explicit values. Node's built-in type stripping and erasableSyntaxOnly (TS 5.8) reject enums because they aren't erasable syntax, which pushes modern code toward unions or as const objects.

Code Example

// Preferred alternative to enum
const Status = { Active: "active", Banned: "banned" } as const;
type Status = (typeof Status)[keyof typeof Status]; // "active" | "banned"

function setStatus(s: Status) {}
setStatus(Status.Active);
setStatus("banned");

Key Points

  • Unions: zero runtime cost
  • as const objects give runtime values + types
  • Enums emit JS objects
  • const enum issues with isolatedModules
  • Type stripping doesn't support enums

More most-asked TypeScript Developer questions

← All TypeScript Developer questions