TypeScript · Types that pay for themselves
How do enums work and when should you use them?
Short answer
Enums define a named set of constants; numeric enums have runtime objects and reverse mappings, while string enums are clearer in logs. For most app state, a union of literals is simpler and erases completely.
An enum creates a runtime object whose members are constants. Numeric members are auto-incremented and also produce a reverse mapping from value to name. String members must be initialized explicitly and do not get a reverse mapping, which makes them easier to read in logs and API payloads.
enum Status {
Idle = "idle",
Loading = "loading",
Error = "error",
}
function render(status: Status): string {
return "State: " + status;
}
render(Status.Loading);Runtime behavior and trade-offs
- Enums emit a JavaScript object, so they add runtime code
- Numeric enums allow reverse lookups, which can be surprising
- String enums are explicit and serialize predictably
- Const enums are inlined but have limitations with isolatedModules and cross-package use
- A union of string literals erases completely and narrows naturally
For application state, a literal union is often the better default: it has no runtime cost, works with discriminated unions and is easy to derive from an API response. Enums are reasonable when a stable runtime object is genuinely useful or when a public API already exposes one.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What JavaScript does an enum emit?
- 2Why can numeric enums be surprising?
- 3What are the limitations of const enums?
- 4When would you choose a literal union over an enum?
Say it in the interview
Enums create a named set of constants. String enums produce readable values at runtime, while numeric enums also generate reverse mappings. I generally prefer a union of string literals for application state because it erases completely and works naturally with narrowing. I use enums when a stable runtime object is genuinely useful or when a public API already exposes one.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.