Introduction
Many values in a program come from a fixed list: directions, log levels, sizes, days of the week. Plain strings let typos through; TypeScript gives two better tools. Enums name a set of constants, and literal types made with as const turn a constant array or object into a union of its exact values. This lesson compares them.
How it works
An enum lists named members:
enum Direction { Up, Down, Left, Right } // 0, 1, 2, 3
enum Level { Info = "INFO", Warn = "WARN" } // string values
A numeric enum numbers its members from 0, unless you give values. Unlike interfaces and type aliases, an enum is not erased: it becomes a real JavaScript object. A numeric enum also maps back from number to name, so Direction[2] is "Left". That makes numeric enums compact but unreadable in output: a log shows 2, not Left. A string enum gives each member a string value, which reads well wherever it is printed. Use an enum member through the enum's name: Level.Warn.
as const is the other approach. Applied to an array or object, it makes it deeply readonly and keeps every value's literal type:
const SIZES = ["small", "medium", "large"] as const;
type Size = (typeof SIZES)[number]; // "small" | "medium" | "large"
Here typeof SIZES in a type position means "the type of the variable SIZES", a readonly tuple of three literals, and indexing it with number gives the union of its items. In the same way, for an object, keyof typeof PRICES is the union of its keys. The list of values exists once, as data, and the type follows it automatically: add "huge" to the array and the type Size includes it.
Which to choose? Many TypeScript teams prefer literal unions and as const, because they are plain JavaScript values with no extra run-time object, and a string such as "small" can be passed straight in. Enums are useful when the members need names that differ from their values, or when you want the reverse lookup of a numeric enum.
Example
// Enums, and literal types made from a constant array or object with as const.
enum Direction {
Up,
Down,
Left,
Right,
}
enum Level {
Info = "INFO",
Warn = "WARN",
}
const SIZES = ["small", "medium", "large"] as const;
type Size = (typeof SIZES)[number]; // "small" | "medium" | "large"
const PRICES = { small: 2, medium: 3, large: 4 } as const;
function log(level: Level, message: string): string {
return "[" + level + "] " + message;
}
console.log(Direction.Left, Direction[Direction.Left]);
console.log(log(Level.Warn, "disk almost full"));
const size: Size = "medium";
console.log(size, PRICES[size], SIZES.length);Line by line
Directionis numeric:Direction.Leftis 2, andDirection[2]gives back"Left".Levelis a string enum; printingLevel.WarnshowsWARN.SIZESwithas constis a readonly tuple, andSizeis the union of its three values.PRICES[size]is allowed becausesizecan only be one of the object's keys.
Expected result
2 Left
[WARN] disk almost full
medium 3 3
In the real world
String enums and literal unions name HTTP methods, log levels, user roles and feature flags. Configuration objects declared as const drive both the program and its types, such as a table of routes from which the type of every valid path is derived. Code generators produce enums from database schemas and API definitions.
Common mistakes
- Printing numeric enums in logs and then not knowing what
2meant. - Mutating a const array and expecting the type to change: with
as const, the array is readonly. - Forgetting typeof in a type:
keyof PRICESis an error, because PRICES is a value; writekeyof typeof PRICES. - Comparing enum members with plain strings in a numeric enum, where the values are numbers.
Best practices
- Prefer string enums to numeric ones when values are printed or stored.
- Keep a list of allowed values once,
as const, and derive its type from it. - Use a literal union for small sets that callers write by hand, such as
"asc" | "desc".
Summary
Enums name fixed sets of values and exist at run time, numeric ones counting from 0 with a reverse lookup, string ones with readable values. as const keeps the literal types of constant data, and typeof and keyof derive union types from it, so the list of values and its type never disagree.
Quick check
Key takeaways
- Enums name a fixed set of values and become real objects in the JavaScript.
- String enums print readable values; numeric enums count from 0 and can be looked up in reverse.
- as const plus typeof and keyof derive literal unions from data, with no enum at all.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.