Numeric Enums

What is an Enum?

An enum is a named set of constants. Numeric enums start at 0 and count up, unless you give values. Unlike most TypeScript features, an enum creates a real JavaScript object at runtime.

Example

Numeric enums also have a reverse mapping: Priority[2] gives the name "High".

enum Priority {
  Low,      // 0
  Medium,   // 1
  High,     // 2
}

enum HttpStatus {
  OK = 200,
  Created = 201,
  NotFound = 404,
}

const p: Priority = Priority.High;
console.log(p, Priority[p]);
console.log(HttpStatus.NotFound);
console.log(Priority);

Output

2 High
404
{ '0': 'Low', '1': 'Medium', '2': 'High', Low: 0, Medium: 1, High: 2 }

The Weakness of Numeric Enums

Example

Before TypeScript 5.0 any number could be assigned to a numeric enum. TypeScript 5 rejects a literal that is not a member (TS2322), but numeric values are still hard to read in logs and databases: what does status 2 mean?

enum Priority { Low, Medium, High }
const p: Priority = 7;

Compiler output (tsc)

Line 2: error TS2322: Type '7' is not assignable to type 'Priority'.