Enums

A named set of related constants under one type, so you refer to them by name instead of a raw value.

What is it?

Some values are one of a small, fixed set of options: a direction, a status, a day of the week. You could use plain strings or numbers ("UP", 0, 1) throughout your code, but nothing groups them, and typos like "Up" instead of "UP" are easy to make and hard to catch.

An enum ("enumeration") groups related named constants under one type. You declare the names once. TypeScript accepts each name as a valid value and rejects any string or number that isn't one of them.

Explain like I'm 10

An enum is like a washing machine dial: Delicate, Normal, Heavy Duty. No in-between settings and no typing your own; you pick one of the fixed, labeled positions.

Examples

A basic numeric enum

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

let move: Direction = Direction.Up;
console.log(move); // 0 — enum members auto-number from 0 by default

function walk(direction: Direction) {
  console.log(`Walking ${Direction[direction]}`);
}

walk(Direction.Left);

Each Direction member gets a number automatically, starting at 0. Direction[direction] looks the name up from its number, which only numeric enums support.

A string enum

enum OrderStatus {
  Pending = "PENDING",
  Shipped = "SHIPPED",
  Delivered = "DELIVERED",
}

function ship(status: OrderStatus) {
  if (status === OrderStatus.Pending) {
    console.log("Preparing shipment...");
  }
}

ship(OrderStatus.Pending);
ship("PENDING" as OrderStatus); // works, but requires an explicit cast

A string enum gives each member a readable string instead of an auto-incrementing number, so logs and debugging output are much clearer.

How it works

Unlike an interface or type alias, an enum generates real JavaScript: an object mapping each member name to its value (and, for numeric enums, values back to names too). Direction.Up compiles to reading a property off that object at runtime.

That makes enums one of the few TypeScript-only features that produce runtime code.

Why does it exist?

Enums name each option in a small, fixed set. Code reads clearly (OrderStatus.Shipped instead of a bare "SHIPPED" string everywhere), and the compiler catches typos instead of them becoming silent runtime bugs.

When to use it

Use an enum for a small, fixed set of related options that code refers to by name: status codes, categories, directions, modes. Prefer string enums over numeric ones when the value may be logged, displayed or sent over the network, since the string explains itself.

When not to use it

For a simple set of strings, many teams prefer a union of string literal types (type Status = "pending" | "shipped" | "delivered"). It needs no import, generates no runtime code and works naturally with plain values from APIs. Use an enum when you want its grouping and reverse lookup.

Common mistakes

  • Forgetting numeric enum members auto-increment from 0, so inserting a member in the middle shifts the number of every member after it.

  • Assuming an enum is compile-time only like an interface. It generates a real JavaScript object at runtime.

  • Habitually casting raw strings to a string enum ("PENDING" as OrderStatus) instead of using the member, which undoes some of the safety enums provide.

Practice exercises

  1. Easy:

    Create a numeric enum TrafficLight with Red, Yellow and Green, and write a function that logs a message for each value.

  2. Medium:

    Convert TrafficLight to a string enum with explicit values ("RED", "YELLOW", "GREEN"). In a comment, explain why that may be better for logging.

  3. Hard:

    Rewrite the TrafficLight string enum as a union of string literal types, and write a function that works the same with both versions. Note what changes at the call sites and what doesn't.

Interview questions

What problem does an enum solve compared to scattering raw string or number literals like `"UP"` or `0` through the code?

It groups a fixed set of values under one named type, so the compiler catches typos (like "Up" instead of "UP") that would otherwise be silent runtime bugs.

Do TypeScript enums exist at runtime, unlike interfaces and type aliases?

Yes. An enum compiles to a real JavaScript object mapping names to values, so Direction.Up reads a property off that object at runtime.

What does `Direction.Up` compile down to at runtime?

A property lookup on the generated enum object, reading the number (or string) stored under the Up key.

Why does `Direction[direction]` work to look up a member's name from its value for a numeric enum?

For numeric enums only, TypeScript generates a reverse mapping: the object maps names to numbers and numbers back to names.

Given `enum Direction { Up, Down, Left, Right }`, what is the runtime value of `Direction.Down`?

1. Members auto-number from 0 in declaration order: Up is 0, Down is 1, and so on.

What happens to the values of later members if you insert a new member in the middle of a numeric enum's declaration?

Every member after it silently gets a new number, which can break code or stored data that relied on the old values.

How do string enums avoid the member-reordering pitfall numeric enums have?

Each member has an explicit, fixed string value, so reordering the declarations changes nothing.

What does `console.log(move)` print given `let move: Direction = Direction.Up;` with `Direction` declared as a plain numeric enum?

0. Direction.Up is the first member, and numbering starts at 0.

Why does `ship("PENDING" as OrderStatus)` need an explicit cast rather than being assignable directly?

A string literal like "PENDING" isn't treated as the enum member OrderStatus.Pending, even with the same value. TypeScript needs an explicit assertion to accept it as an OrderStatus.

What's a common alternative to an enum for representing a small, fixed set of string options, and what does it trade away?

A union of string literals, like type Status = "pending" | "shipped". It needs no import and generates no runtime code, but loses the enum's grouping under one named value and (for numeric enums) reverse lookup.

Between an enum and a union of string literals, which one leaves compiled JavaScript output behind, and which is fully erased?

An enum generates a runtime object. A union of string literals is compile-time only and fully erased.

Why might a string enum be preferable to a numeric enum specifically when the value will be logged, displayed, or sent over a network?

Its runtime value is a readable string like "SHIPPED". A numeric enum's value is a bare number, meaningless unless you know the declaration order.

What breaks if you treat an enum as a purely compile-time construct, the same way you'd treat an interface?

Interfaces are erased, but an enum produces a runtime JavaScript object. Forgetting that can cause surprises around bundle size, reverse lookups, or the enum object being inspectable at runtime.

What changes at the call sites if you convert a numeric `TrafficLight` enum to a string enum with explicit values?

Nothing: TrafficLight.Red works the same. Only each member's runtime value changes, from an auto-numbered integer to the string you assigned.

A function expects `status: OrderStatus`, but a caller has a plain string `"PENDING"` from a JSON API response. Why does passing it directly fail, and what are two ways to fix it?

A plain string isn't typed as the enum, even if the value matches. Either cast it ("PENDING" as OrderStatus) or, often better, model the field as a union of string literals so API strings are assignable without a cast.

Why can generating a real runtime object for every enum be a downside compared to a union of string literals, from a bundle-size perspective?

The enum object (plus reverse-mapping entries for numeric enums) ships to the client as real code. A union of string literals is erased and adds nothing.

TypeScript numeric enums are known to accept any number as assignable to the enum type, not just its declared members — why is this a notable safety gap compared to string enums?

Numeric enums are just numbers underneath, so for backward compatibility TypeScript lets a number be assigned without error. String enum members are checked against their declared strings, so string enums are stricter about invalid values.

Why is `OrderStatus.Pending === OrderStatus.Shipped` guaranteed to be `false`?

Each member gets its own distinct value (a unique auto-number or a unique explicit string), so no two members share a runtime value.