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 constobjects give runtime values + types- Enums emit JS objects
const enumissues with isolatedModules- Type stripping doesn't support enums
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?