TypeScript by Example

Enums

Numeric and string enums, reverse mapping, runtime emit, and why string values are safer.

Enums define named constants. Unlike type aliases, a TypeScript enum emits a JavaScript object.

Numeric enums auto-increment from 0 and generate a reverse mapping.

enum Direction {
  Up,
  Down,
  Left,
  Right,
}
 
console.log(Direction.Up); // 0
console.log(Direction[0]); // "Up"

String enums have readable serialized values and no reverse mapping.

enum Status {
  Pending = "PENDING",
  Active = "ACTIVE",
  Deleted = "DELETED",
}
 
function printStatus(s: Status): void {
  console.log(`Status is: ${s}`);
}

In production

Numeric enums are risky in API code because 0 is falsy. String enums are safer, but they still emit a runtime object. For most contract types, prefer string literal unions.

Enjoyed this? Get more software craft delivered to your inbox.