QuizNot attempted
Enums vs unions
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
enumemits a runtime object, doesn't work with erasable-only type stripping (Node's built-in stripping,--erasableSyntaxOnly), and numeric enums accept anynumber. - 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.