Skip to content

QuizNot attempted

Enums vs unions

Why do many teams prefer type Status = "idle" | "loading" (or an as const object) over enum Status?
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Unions are erased at compile time (zero runtime code) and work with plain strings; enums emit runtime objects, and numeric enums still accept any number-typed value
  • A string-literal union is erased at compile time (zero runtime code) and accepts plain strings, while an enum emits a runtime object, doesn't work with erasable-only type stripping (Node's built-in stripping, --erasableSyntaxOnly), and numeric enums accept any number.
  • Not deprecated: enums are still supported.
  • Not faster at runtime: both compare strings or numbers
  • the difference is emitted code.
  • Not 'can't use in switch': enums switch fine.
  • A const object plus typeof obj[keyof typeof obj] gives a value and a type.