TExcelTAD
Home › TypeScript › TS Enums

TypeScript Enums

An enum (short for enumeration) is a named set of related constants — directions, order statuses, log levels. Instead of scattering magic numbers or strings through your code, you refer to Direction.Up or Status.Shipped, and the compiler makes sure only valid members are used.

Enums are one of the few TypeScript features that are not just type annotations: they generate a real JavaScript object at runtime.

Numeric enums

By default, members are numbered from 0, each one getting the next number:

ts · try it yourself
enum Direction {
  Up,
  Down,
  Left,
  Right,
}

let heading: Direction = Direction.Left;
console.log(heading);
console.log(Direction.Up, Direction.Right);
2
0 3

You can set the starting value, or give each member an explicit value. Members after an initialised one continue counting from it:

ts · try it yourself
enum HttpCode {
  Ok = 200,
  Created,          // 201
  BadRequest = 400,
  Unauthorized,     // 401
  NotFound = 404,
}

console.log(HttpCode.Created, HttpCode.Unauthorized, HttpCode.NotFound);
201 401 404

Reverse mapping

Numeric enums also map values back to names, because the generated object contains both directions:

ts · try it yourself
enum Level {
  Debug,
  Info,
  Warn,
  Error,
}

console.log(Level[2]);
console.log(Level);
Warn
{
  '0': 'Debug',
  '1': 'Info',
  '2': 'Warn',
  '3': 'Error',
  Debug: 0,
  Info: 1,
  Warn: 2,
  Error: 3
}

String enums

Each member of a string enum must be initialised with a string. String enums don't have reverse mappings, but their values are readable when logged or stored — usually the better choice:

ts · try it yourself
enum OrderStatus {
  Pending = "PENDING",
  Shipped = "SHIPPED",
  Delivered = "DELIVERED",
}

function describe(status: OrderStatus): string {
  switch (status) {
    case OrderStatus.Pending:
      return "Waiting for payment";
    case OrderStatus.Shipped:
      return "On its way";
    case OrderStatus.Delivered:
      return "Enjoy!";
  }
}

const current = OrderStatus.Shipped;
console.log(current, "-", describe(current));
SHIPPED - On its way

Note that the switch covers every member, so TypeScript knows describe always returns a string — no default needed.

Enums are type-safe

A variable of an enum type only accepts members of that enum. With string enums, even a string with the same value is rejected — you must go through the enum:

ts · try it yourself
enum OrderStatus {
  Pending = "PENDING",
  Shipped = "SHIPPED",
}

let s: OrderStatus = OrderStatus.Pending;
s = "SHIPPED";
s = OrderStatus.Cancelled;
main.ts(7,1): error TS2322: Type '"SHIPPED"' is not assignable to type 'OrderStatus'.
main.ts(8,17): error TS2339: Property 'Cancelled' does not exist on type 'typeof OrderStatus'.

Const enums

A const enum is completely erased at compile time: every use is replaced by its value, and no object is generated. That produces smaller output, but you lose the runtime object (no Object.values, no reverse mapping), and some tools that compile one file at a time can't handle them.

ts
const enum Size {
  Small = "S",
  Large = "L",
}
const s = Size.Large;   // compiles to: const s = "L";

Iterating over an enum

Because a (non-const) enum is a real object, you can loop over it. For string enums Object.values gives exactly the values:

ts · try it yourself
enum Color {
  Red = "red",
  Green = "green",
  Blue = "blue",
}

for (const c of Object.values(Color)) {
  console.log(c);
}
console.log(Object.keys(Color).length);
red
green
blue
3

Enums or union types?

Many TypeScript developers prefer a union of string literals over enums, because it's pure type information with no runtime code:

ts
type OrderStatus = "PENDING" | "SHIPPED" | "DELIVERED";
enum union of literals
Runtime object yes (can iterate) no
Accepts a plain "SHIPPED" string no yes
Works with type-stripping tools (--erasableSyntaxOnly) no yes
Refactoring a value change it in one place change every usage

Tip: Both are fine. Pick one style for your project and stay consistent. If you need a list of all values at runtime, use an enum or an as const array.

Test yourself

In enum E { A, B, C }, what is the value of E.C?

  1. "C"
  2. 2
  3. 3
  4. undefined

Which kind of enum supports reverse mapping (E[0] gives the name)?

  1. String enums
  2. Numeric enums
  3. Const enums
  4. All enums

With enum S { On = "ON" }, is let x: S = "ON" allowed?

  1. Yes, the values are equal
  2. No, you must write S.On
  3. Only with a const enum
  4. Only at runtime