Skip to the solution
MediumFrontend11 min read

What are enums and what are their trade-offs?

948 views

The problem

Question presented to candidate: "What are enums in TypeScript, and would you use them in a new codebase? Compare numeric enums, string enums, const enum, and a union of string literals or an as const object."

What a strong answer should cover:

  • An enum is one of the few TypeScript features that emits run-time code: a real object, and for numeric enums a reverse mapping from number to name
  • Numeric enums auto-increment and accept numbers; since 5.0 an out-of-range literal is rejected, but any non-literal number still is not
  • String enums have no reverse mapping and are opaque: the raw string "ACTIVE" is not assignable to Status, and two enums with the same values are not interchangeable
  • const enum is inlined by a full tsc build but not by single-file transpilers, and isolatedModules forbids ambient const enums
  • Alternatives: a union of string literals (zero run-time cost) or an as const object plus a derived union (named constants, easy iteration, run-time validation)
  • Trade-offs today: erasableSyntaxOnly (TypeScript 5.8) and Node type stripping reject enums because they are not erasable syntax

Code / implementation expected: Optional β€” define a string enum and the equivalent as const object, and show how each is used and iterated.

  • enums

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptNumeric and string enums at run time and in the checker
TypeScriptAlternatives: a literal union and an as const object

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 24 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How does TypeScript 5.5 infer type predicates for `Array.filter` automatically?

Continue