Enums and their alternatives

Intermediate · 9 min

How `enum` and `const enum` work, why they are not erasable syntax, and when an `as const` object with a derived union is the better choice.

Before thisUnion and literal typesReadonly and immutability

Matt Pocock · 9 min

Enums and their alternatives

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Matt PocockReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An `enum` declares a set of named constants and a type with the same name in one statement; numeric enums auto-number from 0 and get a reverse mapping, string enums do not.
  • Unlike most TypeScript, an enum is not erased: it compiles to a real JavaScript object, and string enum members accept only the enum, not the equivalent string literal.
  • A `const enum` is inlined at each use and leaves no object behind, but it depends on the compiler seeing across files, which breaks under per-file transpilers and `isolatedModules`.
  • Because they generate code, enums are rejected by `erasableSyntaxOnly` and cannot run under Node's built-in type stripping, which only removes type syntax.
  • An `as const` object plus a union type derived from it gives the same named constants and a closed set of values using only erasable syntax, and plain string literals are accepted.
  • Enums remain a reasonable choice in codebases compiled by `tsc` whose teams value the single declaration; the alternatives matter most where code is run by type-stripping tools.

The problem enums were built for

Programs are full of small fixed sets: order statuses, log levels, user roles, directions. You want a name for each value, so you write Status.Shipped rather than a bare 2 or "shipped", and you want a type that accepts only those values. Many languages have a dedicated construct for this, and TypeScript added one early: enum. It works, and lots of code uses it. It also sits awkwardly with how the rest of TypeScript works, and that is why the community is split on it. This lesson presents both sides.

How enums work

A numeric enum numbers its members from zero:

enum Direction {
  Up,
  Down,
  Left,
  Right,
}

function move(d: Direction) {
  return d;
}

move(Direction.Up); // fine
console.log(Direction.Up); // 0
console.log(Direction[0]); // "Up": the reverse mapping

A string enum gives each member an explicit value:

enum Status {
  Active = "ACTIVE",
  Suspended = "SUSPENDED",
}

function setStatus(s: Status) {
  return s;
}

setStatus(Status.Active); // fine
setStatus("ACTIVE"); // Error: Argument of type '"ACTIVE"' is not assignable to parameter of type 'Status'.

That last error surprises people. The runtime value of Status.Active is the string "ACTIVE", but a string enum treats its members as distinct from plain strings. Some teams like that: every value must come through the enum, so finding all uses is a single search. Others find it a nuisance, especially when values come from JSON and have to be cast. Numeric enums are looser: an ordinary number variable is accepted where a Direction is expected.

Enums are not erased

The core of the debate is this. Almost all TypeScript syntax disappears on compilation; delete the annotations and you have the JavaScript. Enums don’t work that way. enum Direction compiles to real code, roughly:

var Direction;
(function (Direction) {
  Direction[(Direction["Up"] = 0)] = "Up";
  Direction[(Direction["Down"] = 1)] = "Down";
})(Direction || (Direction = {}));

That used not to matter much, since tsc or a bundler generated it. It matters more now. Node can run .ts files directly through type stripping, which simply blanks out type syntax; it doesn’t generate code, so an enum is a syntax error there. TypeScript 5.8 added the erasableSyntaxOnly flag to report any syntax that needs generated code, enums included, so that a codebase can guarantee it runs under these tools. The running TypeScript without a build step lesson covers that setup.

const enum

A const enum is inlined: every Level.Debug is replaced with its value, and no object is emitted:

const enum Level {
  Debug = 0,
  Info = 1,
}

const current = Level.Info; // compiles to: const current = 1

To inline it, the compiler has to read the enum’s declaration, which may be in another file. Transpilers such as esbuild and SWC compile one file at a time and can’t do that, which is why isolatedModules restricts const enum usage. It also isn’t erasable: the use sites still need rewriting. In most modern projects it causes more trouble than it saves.

The alternative: an as const object and a derived union

You can get named constants and a closed type from plain JavaScript plus erasable types:

const Status = {
  Active: "ACTIVE",
  Suspended: "SUSPENDED",
} as const;

type Status = (typeof Status)[keyof typeof Status]; // "ACTIVE" | "SUSPENDED"

function setStatus(s: Status) {
  return s;
}

setStatus(Status.Active); // fine
setStatus("ACTIVE"); // fine: a plain literal is accepted
setStatus("DELETED"); // Error: Argument of type '"DELETED"' is not assignable to parameter of type 'Status'.

The object is ordinary JavaScript, so it survives type stripping. as const keeps each value as a literal, as covered in the readonly lesson. The type line reads: take the object’s type, take its keys, and look up the value type at each key. The typeof and keyof operators get a lesson of their own later; for now, the line is a pattern to copy. Giving the type and the object the same name is legal, because types and values live in separate namespaces.

If you don’t need named constants at all, a bare union like type Status = "ACTIVE" | "SUSPENDED" from the union and literal types lesson is simpler still.

Choosing, fairly

Think of an enum as a vendor-specific connector and the as const pattern as a standard socket. The vendor connector is neat and does its job, but only devices built for that vendor can use it.

Enums still have real advantages: one declaration gives both the names and the type, the intent is obvious to readers from other languages, and the strictness of string enums can be a feature. In a codebase compiled by tsc or a full bundler, they work fine, and many large frameworks and libraries use them.

The alternatives win where erasability matters (Node type stripping, erasableSyntaxOnly), where values arrive as plain strings from APIs, and where you would rather avoid numeric enums’ loose checking. For new code, the as const object plus derived union is the safer default; existing enums are rarely worth a rewrite on their own.

About the video

Matt Pocock’s video argues against enums. He walks through the surprises: numeric enums’ reverse mapping, string enums rejecting matching strings, and the as const object with a derived union that he recommends instead. The demonstrations are accurate and worth seeing, but the video is one side of the argument. It predates erasableSyntaxOnly, which is now the strongest technical point against enums, and his follow-up in the links covers that flag. James Q Quick’s video in the links makes the case that enums are often fine; watching both gives a fair picture.

Check yourself

  1. 01What does `enum Direction { Up, Down }` compile to, and why does that make enums unusual in TypeScript?

    It compiles to a JavaScript object mapping `Up` to `0`, `Down` to `1`, and the numbers back to the names. Almost every other TypeScript feature disappears when compiled; enums add runtime code, which is why type-stripping tools can't handle them.

  2. 02With `enum Status { Active = "ACTIVE" }`, why does `setStatus("ACTIVE")` fail when `setStatus` takes a `Status`?

    String enum members behave nominally: only values written through the enum, like `Status.Active`, are accepted, even though the runtime value is the same string. Callers must import the enum to use it.

  3. 03Why do tools that compile one file at a time struggle with `const enum`?

    A `const enum` is replaced by its literal values at every use site, so the compiler needs to read the enum's declaration, which may live in another file. A transpiler working on a single file can't see it, which is why `isolatedModules` reports errors for this pattern.

  4. 04How do you get a type for the values of `const Role = { Admin: "admin", User: "user" } as const`?

    Write `type Role = (typeof Role)[keyof typeof Role]`. `typeof Role` takes the object's type, `keyof` gives its keys, and indexing with them collects the value types, producing `"admin" | "user"`.

  5. 05What does the `erasableSyntaxOnly` flag do?

    It reports an error for any TypeScript syntax that produces runtime code, such as enums, namespaces containing values, and constructor parameter properties. Code that passes the flag can be run by simply deleting the type annotations, which is what Node's type stripping does.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark