All academies
Roadmap/Intermediate

Level 8

Enums

Understand numeric and string enums, how they behave at runtime, const enums, and why modern TypeScript often prefers literal union types instead.

18 min read + quiz

What Enums Are For

An enum (enumeration) defines a named set of related constants: the four cardinal directions, the states of an order, the levels of a logger. Instead of scattering magic numbers or raw strings through your code, you refer to members by meaningful names: Direction.North, OrderState.Shipped, LogLevel.Warn.

Enums are unusual among TypeScript features: they are NOT erased at compile time. An enum compiles to a real JavaScript object that exists at runtime, which means you can iterate over it, look values up dynamically, and pass it around. Every other type-level construct you have learned vanishes during compilation; enums generate code.

That runtime footprint is both the point and the controversy. It enables things unions cannot do, but it also means enums add output size and behave in ways that surprise people who expect types to be free. We will look at both sides honestly.

enum LogLevel {
  Debug,   // 0
  Info,    // 1
  Warn,    // 2
  Error,   // 3
}

function log(level: LogLevel, message: string): void {
  if (level >= LogLevel.Warn) {
    console.log("[IMPORTANT] " + message);
  } else {
    console.log(message);
  }
}

log(LogLevel.Info, "Server started");
log(LogLevel.Error, "Disk full");

A numeric enum: members auto-number from 0, and comparisons use those numbers.

Numeric Enums and Reverse Mapping

By default, enum members receive ascending numbers starting at 0. You can set explicit values ('Debug = 1'), and subsequent members continue counting from there. Numeric values make enums comparable and orderable, which suits concepts like log levels where Warn being 'greater than' Info is meaningful.

Numeric enums compile to an object with a peculiar extra feature: reverse mapping. The generated object maps names to values AND values back to names, so LogLevel[2] returns the string "Warn". This is handy for debugging output, but it also means Object.keys on a numeric enum returns twice as many entries as you might expect, half names, half stringified numbers.

A real weakness to know: for many years TypeScript allowed ANY number to be assigned where a numeric enum was expected, and even in modern versions the checking around numeric enums is looser than for string enums or unions. If you use enums, prefer string enums for the stronger guarantees.

enum Status {
  Pending = 1,
  Active,     // 2 (continues from 1)
  Closed,     // 3
}

console.log(Status.Active);    // 2
console.log(Status[2]);        // "Active" - reverse mapping

// The compiled object contains BOTH directions:
// { "1": "Pending", "2": "Active", "3": "Closed",
//   Pending: 1, Active: 2, Closed: 3 }

Numeric enums generate a two-way lookup object: names to numbers and numbers back to names.

String Enums

String enums require an explicit string value for every member: 'North = "NORTH"'. They give up auto-numbering and reverse mapping but gain something more valuable: readable values everywhere. When a string enum value lands in a log file, a database row, or a network payload, you see "SHIPPED" instead of a mysterious 2.

String enums are also checked more strictly. You cannot assign an arbitrary string where a string enum is expected, and you cannot even assign a raw "NORTH" literal; you must use Direction.North. This nominal-flavored behavior is unusual in structurally-typed TypeScript, and some teams value it precisely because it forces every usage through the named constant.

The debugging and serialization benefits make string enums the recommended flavor whenever you choose to use enums at all. Reserve numeric enums for cases where ordering or bit-flag arithmetic genuinely matters.

enum Direction {
  North = "NORTH",
  South = "SOUTH",
  East = "EAST",
  West = "WEST",
}

function walk(dir: Direction): string {
  return "Walking " + dir;   // the value IS the readable string
}

console.log(walk(Direction.North));  // "Walking NORTH"

// Strictness: raw strings are rejected, even matching ones.
// walk("NORTH");
// Error: '"NORTH"' is not assignable to parameter of type 'Direction'.

String enums serialize readably and reject raw strings - only the named member is accepted.

const enums and Their Trade-offs

Prefixing an enum with const ('const enum Flag { ... }') tells the compiler to inline the values: every usage of Flag.On is replaced with its literal value in the output, and no runtime object is generated at all. You get enum ergonomics with zero runtime cost.

The catch is tooling compatibility. Inlining requires the compiler to see the enum's definition while compiling each file that uses it, but popular build tools (Babel, esbuild, SWC, and bundler pipelines built on them) compile files one at a time in isolation and cannot resolve const enum values across files. The isolatedModules setting, which those tools require, restricts const enums for exactly this reason.

Because of these constraints, most style guides say to avoid const enums in application code and libraries. If the runtime cost of a regular enum bothers you, the better modern answer is usually a union type, which is our final topic.

const enum Flag {
  Off = 0,
  On = 1,
}

const current = Flag.On;
console.log(current);

// Compiled output contains no Flag object at all - just:
// const current = 1; /* Flag.On */
// But this inlining breaks under isolatedModules / esbuild / Babel.

const enums inline to bare literals - efficient, but incompatible with single-file build tools.

Enums vs Literal Unions

You already know literal unions: 'type Direction = "north" | "south" | "east" | "west"'. They cover most enum use cases with zero runtime code, no import needed at usage sites (any matching string literal works), and perfect compatibility with every build tool. For plain 'one of these values' modeling, unions are the modern default recommendation.

Enums still earn their place when you need the runtime object: iterating over all members, mapping names to values dynamically, or attaching a stable serialized value (string enums) that must never drift from the constant's name. Enums also give you a single rename-safe symbol; renaming a union member is a find-and-replace across every string literal.

If you like union ergonomics but want an enum-like object, the 'as const object' pattern gives you both: define a plain object with 'as const', derive the union type from its values, and you get runtime iteration plus compile-time literal checking, with no enum quirks. Many codebases have standardized on this pattern.

// The as-const pattern: enum-like object + union type, no enum.
const STATUS = {
  Pending: "pending",
  Active: "active",
  Closed: "closed",
} as const;

type Status = (typeof STATUS)[keyof typeof STATUS];
// Status is "pending" | "active" | "closed"

function report(s: Status): string {
  return "Status is " + s;
}

console.log(report(STATUS.Active));  // named constant works
console.log(report("closed"));       // raw literal also works
console.log(Object.values(STATUS));  // runtime iteration works too

The as-const object pattern: runtime iteration like an enum, flexibility of a union.

Try it yourself

This lesson's example is preloaded in the playground — break it, fix it, extend it.

Open in playground

Check your understanding

Question 1 · Multiple choice

How do enums differ from interfaces and type aliases with respect to the compiled JavaScript output?

Question 2 · Predict the output

What does this program print?

enum Level {
  Low = 1,
  Medium,
  High,
}

console.log(Level.High);
console.log(Level[2]);

Question 3 · Find the error

This code fails to compile. What is wrong?

enum Direction {
  North = "NORTH",
  South = "SOUTH",
}

function walk(dir: Direction): string {
  return "Walking " + dir;
}

console.log(walk(Direction.North));
console.log(walk("SOUTH"));

Question 4 · True or false

const enums are always the best choice because they inline values and add zero runtime cost.

Question 5 · Multiple choice

Which requirement genuinely favors an enum (or as-const object) over a plain literal union type?