Enums and alternatives

Topic 2 of 4 in Modelling data7 min readIntermediateFree course

Overview

Many languages have enums — named sets of constants — and TypeScript has them too. You’ll see them in older codebases and some libraries. But they’re one of the few TypeScript features that generate JavaScript, and modern TypeScript code increasingly avoids them. This lesson explains enums, their quirks, and the plain-JavaScript patterns that replace them.

Enums

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

function move(direction: Direction) { … }
move(Direction.Up);

By default members get the numbers 0, 1, 2… You can set values explicitly, including strings:

TypeScript
enum Status {
  Active = "active",
  Banned = "banned",
}

An enum is both a type (Direction) and a value (an object you can use at run time, Direction.Up).

The catch: enums generate code

Enums and their alternatives. enum Status { Active, Banned } exists at run time: it compiles to a real JavaScript object — var Status; (function (Status) { Status[Status[“Active”] = 0] … })(Status || (Status = {}));. A union of literals, type Status = “active” | “banned”, compiles to nothing at all. A const object — const Status = { Active: “active”, Banned: “banned” } as const; type Status = (typeof Status)[keyof typeof Status]; — gives named values AND a type, in plain JavaScript. Node’s built-in TypeScript support and erasableSyntaxOnly reject enums, because they generate code. Prefer unions of literals, or a const object when you also need the values at run time.

Everything else you’ve learned so far is erased when TypeScript becomes JavaScript. Enums aren’t: TypeScript has to write code for them. That has consequences:

  • Node.js can’t run them. Node’s built-in TypeScript support only strips types:

    Text
    SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
  • erasableSyntaxOnly (in this course’s tsconfig, and recommended for any project that strips types) reports them:

    Text
    error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
  • Numeric enums are loosely typed and have reverse mappings. Direction[0] is "Up", and the object contains both names and numbers, which surprises anyone who iterates over it.

Enums aren’t wrong — with tsc or a full compiler like tsx they work fine — but the alternatives are simpler and work everywhere.

Alternative 1: a union of string literals

For most uses, a literal union does everything you need:

TypeScript
type Status = "active" | "banned" | "pending";

function setStatus(status: Status) { … }

setStatus("active");     // ✓ autocompletes
setStatus("actve");
// error TS2345: Argument of type '"actve"' is not assignable to parameter of type 'Status'.
  • Zero run-time code.
  • Values are readable in logs, JSON and databases ("active", not 0).
  • Narrowing and exhaustiveness checks work exactly as in Discriminated unions.

Alternative 2: a const object

When you also want the values as a real object — to loop over them, map them, or write Status.Active — use a const object with as const, and derive the type from it:

TypeScript
const Status = {
  Active: "active",
  Banned: "banned",
  Pending: "pending",
} as const;

type Status = (typeof Status)[keyof typeof Status];   // "active" | "banned" | "pending"

function setStatus(status: Status) { … }

setStatus(Status.Active);   // ✓ enum-like usage
setStatus("banned");        // ✓ a plain string works too
Object.values(Status);      // ["active", "banned", "pending"] — no reverse mapping

The type line reads: “the type of the Status object, indexed by each of its keys” — that is, the union of its values. Using the same name for the value and the type is legal (values and types live in separate namespaces) and makes the pattern feel just like an enum.

For numeric constants, such as levels that need ordering, use numbers as the values:

TypeScript
const LogLevel = { Debug: 0, Info: 1, Warn: 2, Error: 3 } as const;
type LogLevel = (typeof LogLevel)[keyof typeof LogLevel];   // 0 | 1 | 2 | 3

if (level >= LogLevel.Warn) { … }

Quick comparison

enum literal union const object
Run-time code yes none a plain object
Works with type stripping no yes yes
X.Member syntax yes no yes
Iterate over values awkward (reverse mapping) no values to iterate Object.values(X)
Narrowing & exhaustiveness yes yes yes

Reading enum code

You’ll still meet enums in existing projects and in library types. A few facts help when reading them:

  • enum E { A, B } — numeric, starting at 0.
  • enum E { A = "a" } — string enum; no reverse mapping, and you can’t pass a plain "a" where E is expected.
  • const enum E { … } — members are inlined at compile time; also not erasable and discouraged in libraries.
  • declare enum — an enum that exists somewhere else (in a .d.ts file).

Rule of thumb: reach for a literal union first; use a const object when you need the values at run time; leave enums to code that already has them.

Exercise

Log levels without an enum

The starter uses an enum, which Node can’t run and erasableSyntaxOnly rejects. Replace it with a const LogLevel = { Debug: 0, Info: 1, Warn: 2, Error: 3 } as const object and a matching type LogLevel derived from it. Then write levelName(level: LogLevel): string (the key for a value, e.g. 2 → "Warn"), shouldLog(level: LogLevel, minimum: LogLevel): boolean, and log(level: LogLevel, message: string, minimum: LogLevel = LogLevel.Info) that prints [WARN] Disk almost full only when the level is high enough. Separately, define type Theme = "light" | "dark" | "system" and a next(theme: Theme): Theme that cycles through them with a switch. Call everything to show it works.

TypeScript
enum LogLevel {
  Debug,
  Info,
  Warn,
  Error,
}

function log(level: LogLevel, message: string) {
  if (level >= LogLevel.Info) {
    console.log(`[${LogLevel[level].toUpperCase()}] ${message}`);
  }
}

log(LogLevel.Warn, "Disk almost full");

Summary

  • An enum creates both a type and a real JavaScript object; numeric enums also add a reverse mapping.
  • Enums generate code, so Node’s type stripping and erasableSyntaxOnly reject them.
  • A union of string literals is the simplest replacement: type Theme = "light" | "dark".
  • When you also need the values at run time, use a const object as const plus type X = (typeof X)[keyof typeof X].
  • Unions and const objects narrow, autocomplete and check exhaustiveness just like enums.