Sub topic 8
Enums or Literal Unions: How to Choose
This chapter assumes you know basic TypeScript types, functions, object literals, and switch statements. The goal is to choose a good representation when a value must come from a fixed set.
Literal unions: types without runtime output
A literal union is a type made from several exact values. It restricts values during compilation, but it does not create an object in the generated JavaScript.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // OK
move("diagonal"); // ErrorLiteral unions work well when values already come from JSON, HTTP requests, HTML attributes, or another JavaScript system. They also make code easy to compare with ordinary strings.
You can combine literal types with other primitive types:
type Port = 80 | 443;
type Enabled = true | false;
function connect(port: Port, secure: Enabled): void {
console.log({ port, secure });
}In practice, boolean is usually clearer than true | false, but the example shows that exact primitive values can form types.
Enums: named values at runtime
An enum is a TypeScript declaration that normally creates a JavaScript object. It gives related values names and provides a namespace for accessing them.
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
function paint(color: Color): void {
console.log(color);
}
paint(Color.Red); // OK
paint("RED"); // ErrorThe string "RED" has the same runtime value as Color.Red, but TypeScript does not treat the plain string as a Color. Callers must use the enum member.
Enums can also use numbers:
enum Status {
Pending,
Running,
Complete,
}
console.log(Status.Pending); // 0
console.log(Status.Running); // 1
console.log(Status[1]); // "Running"Numeric enum members receive values automatically unless you assign them. This convenience can become a problem when numbers cross an external boundary. A number such as 1 may not explain what it means, and older TypeScript behavior can allow more numeric values than intended.
Compare the choices
| Question | Literal union | Enum |
|---|---|---|
| Does it create a runtime value? | No | Usually yes |
| Can callers pass matching string literals? | Yes | No, for string enums |
| Does it provide named member access? | Not by itself | Yes |
| Does it work naturally with JSON strings? | Yes | Usually requires conversion |
| Does it add emitted JavaScript? | No | Usually yes |
| Is reverse lookup built in? | No | Numeric enums provide it |
Choose a literal union when the set describes data rather than a runtime object:
type Theme = "light" | "dark";
function setTheme(theme: Theme): void {
document.body.dataset.theme = theme;
}
setTheme("dark");Choose an enum when a runtime namespace is useful, when a framework or existing codebase requires enums, or when named members improve the API:
enum Permission {
Read = "read",
Write = "write",
Admin = "admin",
}
function canEdit(permission: Permission): boolean {
return permission === Permission.Write || permission === Permission.Admin;
}A runtime object with a derived union
A constant object gives named runtime values while keeping a literal union for function parameters:
const Theme = {
Light: "light",
Dark: "dark",
} as const;
type Theme = (typeof Theme)[keyof typeof Theme];
function setTheme(theme: Theme): void {
console.log(theme);
}
setTheme(Theme.Dark); // OK
setTheme("light"); // OKas const prevents the property values from widening to string. The typeof operator obtains the object’s type, and keyof obtains its property names. Indexing with those keys produces the union "light" | "dark".
This pattern is often a useful middle ground. It has runtime values like an enum, but it accepts the same string literals used by APIs and configuration files.
Decision diagram
Common errors
Do not assume that an enum and a union with the same values are interchangeable:
enum Mode {
Safe = "safe",
Fast = "fast",
}
type ModeText = "safe" | "fast";
const text: ModeText = "safe";
const mode: Mode = Mode.Safe;
// const invalid: Mode = text; // ErrorIf data arrives as a string, validate it before converting it to an enum. A type annotation does not validate runtime input.
Also avoid numeric enums when the number itself has no stable meaning. Prefer explicit string members or string literal unions for values stored in files, databases, URLs, or messages.
Exercise
You receive "draft", "published", or "archived" from a REST API. You need to compare the values in TypeScript, and no runtime namespace is required. Which representation should you choose, and why?
Show answer
Choose a literal union, such as type State = "draft" | "published" | "archived". It accepts the API’s plain strings and emits no JavaScript.