Explain it simply
Enums, in plain language
Some values in a program can only ever be one item from a short, fixed list. A player in a game moves Up, Down, Left or Right; an order is Pending, Paid or Shipped. Writing those as loose strings or as magic numbers like 0 and 3 invites typos that nobody notices.
An enum gives the whole list one name and gives each option a readable label, so you write Direction.Up instead of remembering that 0 means up. The compiler then only lets you use labels that really exist in the list, and your editor can autocomplete them.
Problem → Why → Solution
The problem: a rule that only lives in a comment
A small game stores the player's direction as a number: 0 means up, 1 down, 2 left and 3 right. That rule lives only in a comment. A few months later someone writes move(4), or compares against 1 when they meant up, and TypeScript is perfectly happy because both are valid numbers. The bug only shows up as a character that refuses to move.
// 0 = up, 1 = down, 2 = left, 3 = right ... hopefully everyone remembers
function move(direction: number) {
if (direction === 0) console.log("Moving up!");
if (direction === 1) console.log("Moving up!"); // wrong number, no error
}
move(4); // no such direction, still compilesWhy the compiler cannot help
The type number describes how a value is stored, not what it means. Thousands of numbers are valid numbers, but only four are valid directions. You need a type whose set of allowed values is exactly the list of options, with names a reader understands.
Core concept: one declaration, a type and a value
An enum declaration does two jobs at once. It creates a type, Direction, whose only allowed values are its members, and it creates a real JavaScript object, also named Direction, that holds those values at runtime. The second part is unusual: almost everything else you write in TypeScript, such as type aliases and interfaces, disappears when the code is compiled, but an enum is emitted as code.
In a numeric enum the first member is 0 by default and every following member is one more than the previous one, so Up is 0, Down is 1, Left is 2 and Right is 3. You can set a starting value (Up = 1) or give every member an explicit number. In a string enum every member must be initialised with a string, such as Paid = "PAID". String enums are easier to debug, because a log line shows "PAID" instead of a bare 1.
| Feature | Numeric enum | String enum |
|---|---|---|
| Default values | 0, 1, 2... counted automatically | none, each member needs a string |
| In logs and JSON | a number such as 2 | readable text such as "LEFT" |
| Reverse mapping | yes: Direction[2] is "Left" | no |
Reverse mapping is the part that surprises people. The object compiled from a numeric enum maps names to numbers and also numbers back to names, which is why Object.keys(Direction) returns eight keys instead of four. A string enum only maps names to values.
What enum Direction { Up, Down } compiles to
--------------------------------------------
TypeScript source JavaScript object at runtime
----------------- ----------------------------
enum Direction { {
Up, // 0 "0": "Up", Up: 0,
Down, // 1 "1": "Down", Down: 1
} }
names -> numbers AND numbers -> namesFinally, an enum is not the only way to model a fixed list. A string-literal union such as type Direction = "up" | "down" gives the same compile-time safety with no runtime code at all, and an as const object gives you both a runtime object and a type. Many teams prefer those today, especially when their tools only strip types instead of transforming code, as you will see below.
- Declare the list once: enum Direction
- Members get values: 0, 1, 2 or strings
- Type: only members are allowed
- Runtime: a real object is emitted
An enum is both a type and a value; that is exactly what separates it from a type alias.
General pattern
enum Name {
First, // 0
Second, // 1
}
enum Label {
A = "A_VALUE", // string members need explicit values
B = "B_VALUE",
}
let current: Name = Name.First;Numeric members count up from 0 unless you set a value; string members must each be initialised. Use the enum name as the type and Name.Member as the value.
Moving a player with an enum
The example declares the four directions of a game, stores the player's current direction in a variable typed with the enum, and compares it with a member.
enum Direction {
Up,
Down,
Left,
Right,
}
let playerDirection: Direction = Direction.Up;
if (playerDirection === Direction.Up) {
console.log("Moving up!");
}Code breakdown
- Lines 1-6
enum Direction {Declares a numeric enum with four members. None has an initialiser, so Up is 0, Down is 1, Left is 2 and Right is 3.
- Line 8
let playerDirection: Direction = Direction.Up;Direction is used twice: first as a type annotation, then as a value read from the runtime object.
- Line 10
if (playerDirection === Direction.Up) {At runtime this simply compares two numbers (0 === 0). A misspelled member such as Direction.Upp is a compile error.
- Line 11
console.log("Moving up!");The condition is true, so this line runs and prints Moving up!.
Moving up!Enum vs union vs as const object
Here is the same fixed list written three ways. The key difference: a plain string literal "PAID" cannot be assigned to a string enum type, you must write Status.Paid, whereas the union accepts "PAID" directly.
// 1. Enum: a type AND a runtime object
enum Status { Pending = "PENDING", Paid = "PAID" }
// 2. String-literal union: a type only, erased when compiled
type StatusUnion = "PENDING" | "PAID";
// 3. as const object: a runtime object plus a type derived from it
const STATUS = { Pending: "PENDING", Paid: "PAID" } as const;
type StatusValue = (typeof STATUS)[keyof typeof STATUS]; // "PENDING" | "PAID"
const a: Status = Status.Paid; // const x: Status = "PAID" would be an error
const b: StatusUnion = "PAID";
const c: StatusValue = STATUS.Paid;
console.log(a, b, c); // PAID PAID PAID| Option | Good fit when |
|---|---|
| enum | the code base already uses enums and the build transforms them |
| String-literal union | you only need type safety, no runtime list of values |
| as const object | you need a runtime list to loop over or validate, plus a type |
Enums and type-stripping tools
Because an enum generates runtime code, tools that only erase type annotations (for example Node.js's built-in TypeScript support) do not run enums by default. With the erasableSyntaxOnly option, added in TypeScript 5.8, the compiler reports enums as errors. const enum, which inlines values, also causes trouble in isolatedModules setups that compile one file at a time.
In real projects
Real project: status values that cross a boundary
In real projects enum values rarely stay inside the code. An order status is stored in a database column, sent in API responses and logged in analytics events. For values that cross such boundaries, use a string enum (or a string union), so anyone reading the data sees "SHIPPED" instead of 2, and reordering members never changes the meaning of stored data.
An incoming string from a request body is not checked by the enum type, though; JSON can contain anything. Use the enum's runtime object to check the value at the boundary:
enum OrderStatus { Pending = "PENDING", Paid = "PAID", Shipped = "SHIPPED" }
const allowed: string[] = Object.values(OrderStatus);
function parseStatus(raw: string): OrderStatus | undefined {
return allowed.includes(raw) ? (raw as OrderStatus) : undefined;
}
console.log(parseStatus("PAID")); // PAID
console.log(parseStatus("REFUNDED")); // undefinedYou will see the same pattern behind dropdown options in admin panels, feature-flag names and user roles such as Admin, Editor and Viewer.
Common mistakes
Common mistakes
1. Looping over a numeric enum and getting numbers too
Because of reverse mapping, Object.keys(Direction) returns eight keys: '0', '1', '2', '3', 'Up', 'Down', 'Left', 'Right'. Build a dropdown from that and you get eight options. Filter out numeric keys with isNaN(Number(key)), or use a string enum, which has no reverse mapping.
2. Storing numeric values, then reordering members
Save 2 (Left) in a database, then insert a new member Stop between Up and Down, and every later number shifts. The stored 2 now means Down, with no error anywhere. Give persisted members explicit numbers or strings.
3. Assuming a numeric enum type blocks every bad number
The compiler rejects a literal such as let d: Direction = 7, but a variable of type number is still assignable to a numeric enum. A 99 that came from JSON or from a calculation can therefore slip through as a Direction. Check outside values at runtime.
Best practices
Best practices
- Prefer string enums or string unions for values that reach logs, databases or APIs.
- If you keep a numeric enum, give every persisted member an explicit number.
- Consider a string-literal union instead of an enum when you need no runtime list.
- Check outside values against Object.values(TheEnum) at the boundary.
Mini challenge
A log-level filter
Model log levels with a numeric enum whose values you choose, then write a function that decides whether a message is important enough to print.
- Declare enum LogLevel with Debug = 10, Info = 20, Warn = 30 and Error = 40.
- shouldLog(level, minimum) returns true when level is at least minimum.
- log(level, message, minimum) prints a line like "[WARN] message", using the reverse mapping LogLevel[level] for the name.
- With minimum set to LogLevel.Warn, only Warn and Error messages appear.
// TODO: declare enum LogLevel with Debug = 10, Info = 20, Warn = 30, Error = 40
function shouldLog(level: LogLevel, minimum: LogLevel): boolean {
// TODO: compare the two numeric values
return false;
}
function log(level: LogLevel, message: string, minimum: LogLevel): void {
// TODO: return early unless shouldLog(level, minimum) is true
// TODO: read the member name with LogLevel[level] and print "[NAME] message"
}
// TODO: call log() once per level, all with minimum = LogLevel.WarnExpected: Only two lines are printed: [WARN] Disk is 91% full and [ERROR] Payment service timed out.
Show hint
Numeric enum members are numbers at runtime, so you can compare them with >= directly. LogLevel[30] gives back "Warn".
Show solution
enum LogLevel {
Debug = 10,
Info = 20,
Warn = 30,
Error = 40,
}
function shouldLog(level: LogLevel, minimum: LogLevel): boolean {
return level >= minimum;
}
function log(level: LogLevel, message: string, minimum: LogLevel): void {
if (!shouldLog(level, minimum)) return;
const name = LogLevel[level].toUpperCase();
console.log(`[${name}] ${message}`);
}
const minimum = LogLevel.Warn;
log(LogLevel.Debug, "Cache miss for user 42", minimum);
log(LogLevel.Info, "Server started on port 3000", minimum);
log(LogLevel.Warn, "Disk is 91% full", minimum);
log(LogLevel.Error, "Payment service timed out", minimum);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An enum names a fixed list and creates both a type and a runtime object.
- Numeric members count up from 0 and have a reverse mapping; string members do not.
- Choose string values for anything that crosses a boundary, and check it at runtime.
- A string-literal union or an as const object is often the simpler choice when you need no runtime code.
TypeScript Handbook — TypeScript