Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Concepts and Comparisons

Enums versus unions in TypeScript

Compare enums, string literal unions and as const objects: emitted code, type safety, iteration, tree shaking and Node type stripping.

TypeScript gives you three ways to say "one of these fixed values": an enum, a union of literal types, and an object frozen with as const. They cover the same need with different trade-offs in emitted code, runtime access and tooling support.

A union of string literals costs nothing at run time. An enum creates a real object. An as const object gives you both: a runtime value to iterate and a derived union type.

TypeScript
enum Direction { Up = "UP", Down = "DOWN" }
type Dir = "UP" | "DOWN";
const DIRS = { Up: "UP", Down: "DOWN" } as const;

Try it

TypeScript The same set three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Strictness of a string enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Comparison

enum Literal union as const object
Emits JavaScript Yes (object) No Yes (object)
Iterate members at run time Yes No Yes
Accepts a raw string literal No (string enums) Yes Yes
Works with Node type stripping No (needs transform) Yes Yes
Reverse lookup (number to name) Numeric enums only No Manual
Autocomplete Yes Yes Yes
Tree shaking Usually poor Not needed Good

Usage notes

  • Default to a union for small closed sets used only in types, such as "asc" | "desc".
  • Choose as const when you also need the values at run time: option lists, validation, UI menus.
  • Choose an enum when the team already uses them, or when you need nominal-like separation: two string enums with identical values are not interchangeable.
  • Numeric enums are loose. Since TypeScript 5.0 an out-of-range numeric literal is an error, but a plain number variable is still assignable to a numeric enum.
  • const enum inlines values, but it is awkward with isolatedModules and tooling; see const enum.
  • erasableSyntaxOnly rejects enums, since they emit code; see erasableSyntaxOnly.
  • Exhaustiveness works equally well with all three through a never check.