TypeScript Enums

TypeScript enums define a set of named constants. Unlike most TypeScript features, an enum also creates a real JavaScript object at runtime, so you can loop over it or look up names.

Numeric Enums

By default, members get numbers starting at 0. You can set the first value and the rest count up. Numeric enums also get a reverse mapping from value to name.

enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}
console.log(Direction.Up, Direction.Right);
console.log(Direction[3]); // reverse mapping
1 4
Left

String Enums

String enums give each member an explicit string value. They are easier to read in logs and JSON, and have no reverse mapping.

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

function label(s: OrderStatus) {
  return s === OrderStatus.Delivered ? "Done" : "In progress";
}
console.log(OrderStatus.Shipped, label(OrderStatus.Delivered));
// label("SHIPPED"); // Error: '"SHIPPED"' is not assignable to 'OrderStatus'.
SHIPPED Done

How Enums Compile

An enum becomes an object in the output JavaScript. This adds code to your bundle, which is one reason some teams avoid them.

// TypeScript
enum Color { Red = "red", Green = "green" }

// compiled JavaScript (simplified)
var Color;
(function (Color) {
  Color["Red"] = "red";
  Color["Green"] = "green";
})(Color || (Color = {}));

Alternatives: Literal Unions and as const

A union of string literals gives the same type safety with zero runtime code. If you also need a runtime object, use an as const object and derive the type from it.

const Role = {
  Admin: "admin",
  Editor: "editor",
  Viewer: "viewer",
} as const;
type Role = (typeof Role)[keyof typeof Role]; // "admin" | "editor" | "viewer"

function canEdit(r: Role) {
  return r !== Role.Viewer;
}
console.log(canEdit("editor"), Object.values(Role).join("/"));
true admin/editor/viewer

Enum Tips

  • Prefer string enums over numeric ones for readable values
  • const enum is inlined at compile time but does not work with some build tools (isolatedModules)
  • Node.js type stripping and the erasableSyntaxOnly option do not support enums
  • For new code, literal unions or as const objects are often the simplest choice

Frequently asked questions

Should I use enums in TypeScript?

They work, but many modern codebases prefer string literal unions or as const objects, which have no runtime cost and fit better with plain JSON data.

What is the difference between enum and const enum?

A regular enum creates an object at runtime. A const enum is replaced with literal values during compilation and leaves no object behind.

How do I get all values of a TypeScript enum?

For a string enum, use Object.values(MyEnum). Numeric enums also contain reverse mappings, so filter out the string keys.