TypeScript Reference ยท Classes, Enums and Decorators
TypeScript enum alternatives
Reference for replacing TypeScript enums with union types and as const objects: how to derive types, iterate values, validate input and keep erasable syntax.
Enums are one of the few TypeScript features that emit their own JavaScript. If you want types only, two patterns cover almost everything enums do: a union of string literals, and a as const object from which you derive a union. Both are erased or ordinary JavaScript, so they work with Node's type stripping and with erasableSyntaxOnly.
The as const object gives you a runtime list of values to loop over and validate against, while the derived union gives you the same compile-time safety as an enum.
const Role = { Admin: "admin", User: "user" } as const; type Role = (typeof Role)[keyof typeof Role]; // "admin" | "user"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
// 1. Pure union type Name = "a" | "b"; // 2. Object plus derived union (same identifier for value and type) const Name = { A: "a", B: "b" } as const; type Name = (typeof Name)[keyof typeof Name]; // 3. Array plus derived union const names = ["a", "b"] as const; type NameFromArray = (typeof names)[number];
| Part | Description |
|---|---|
as const |
Keeps the literal types and makes properties readonly. |
keyof typeof Obj |
The union of property names. Indexing the object type with it gives the union of values. |
(typeof arr)[number] |
The union of an array's element literals. |
Usage notes
- Pros of alternatives: no emitted code, values are plain strings in logs and JSON, literals are accepted without importing anything, and the pattern is compatible with
erasableSyntaxOnlyand type stripping. - Pros of enums: a named namespace with autocomplete on
Enum., nominal typing (an unrelated string is rejected), and numeric reverse lookups. - Declaring the value and the type with the same name is legal because values and types live in separate namespaces; export both with one
export. Record<Union, T>andsatisfiesmake tables that fail to compile when a member is missing.- Numeric enums can be replaced by a numeric
as constobject, but the loose number assignability goes away, which is usually good. - Object.keys returns
string[], so a cast or a typed helper is needed when iterating keys.
Related
- String enums, Numeric enums
- Enums versus unions
- Tutorial: Enums