Sub topic 2
Combining literals into unions
This chapter assumes you know TypeScript's basic types (string, number, boolean, object types) and can annotate function parameters and return types. It also assumes you can read switch statements and object literals in JavaScript. The previous chapter introduced literal types, which are types that hold exactly one value. This chapter combines them into unions, which are the most common way to model a fixed set of values in TypeScript.
What a union of literals is
A union type is written with | and means "a value of any one of these types". When every member is a literal type, the union describes a closed set of allowed values.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // OK
move("diagonal"); // Error: Argument of type '"diagonal"' is not assignable to parameter of type 'Direction'.Direction has exactly four possible values. The compiler rejects every other string, including strings that differ only in case, such as "Up". Editors also use the union to offer autocomplete when you type the argument.
A union is a set, and the order of its members does not matter. "up" | "down" and "down" | "up" are the same type. Repeating a member changes nothing, so "up" | "up" simplifies to "up".
Assignability is subset checking
A value is assignable to a union if its type is assignable to at least one member. For unions of literals this works like set containment. A narrower union can be assigned to a wider one, but not the other way around.
type Direction = "up" | "down" | "left" | "right";
type Movement = Direction | "forward" | "back";
declare const d: Direction;
const m: Movement = d; // OK: every Direction is also a Movement
declare const wide: Movement;
const n: Direction = wide; // Error: Type 'Movement' is not assignable to type 'Direction'.The diagram shows the relationship.
Arrows point in the direction where assignment is allowed. Nothing flows backward. This is the same rule that makes string impossible to assign to Direction.
Mixing kinds of literals
A union can combine string, number, and boolean literals. Members do not need to share a base type.
type Port = 80 | 443 | "auto";
function listen(port: Port): string {
if (port === "auto") {
return "Choosing a free port";
}
return `Listening on ${port}`; // port is 80 | 443 here
}
console.log(listen(443)); // Listening on 443
console.log(listen("auto")); // Choosing a free portNumber literals work the same way as string literals. listen(8080) is an error, because 8080 is not 80 or 443.
The built-in boolean type is itself a union. TypeScript treats boolean as true | false. You can use this to restrict a value to one half:
type Enabled = true;
type Maybe = true | null;null and undefined are also single-value types, so they combine with literals in the same way. Under strictNullChecks, which strict mode enables, "on" | "off" | null models a setting that may be unset.
Narrowing a union
Inside a function, TypeScript tracks which members of a union are still possible. Each comparison removes members from the type on one side of the check. This is called narrowing.
type Direction = "up" | "down" | "left" | "right";
function opposite(direction: Direction): Direction {
if (direction === "up") {
return "down";
}
// direction is now "down" | "left" | "right"
if (direction === "down") {
return "up";
}
// direction is now "left" | "right"
return direction === "left" ? "right" : "left";
}After the first if returns, the compiler knows direction cannot be "up". Narrowing works with ===, !==, switch, and typeof checks. The Port example above used === to separate "auto" from the numbers.
Narrowing also catches impossible comparisons:
type Direction = "up" | "down" | "left" | "right";
function check(direction: Direction): boolean {
return direction === "diagonal";
// Error: This comparison appears to be unintentional because the types
// 'Direction' and '"diagonal"' have no overlap.
}This error often reveals a typo in a string you compare against. It also shows up when a union later loses a member and old code still checks for it.
When a union mixes base types, typeof narrows by kind:
type Port = 80 | 443 | "auto";
function describe(port: Port): string {
if (typeof port === "number") {
return `fixed port ${port}`; // port is 80 | 443
}
return `automatic port (${port})`; // port is "auto"
}Deriving new types from a union
Because a union is a set of types, the standard utility types operate on its members.
Exclude<T, U>removes members ofTthat are assignable toU.Extract<T, U>keeps only the members ofTthat are assignable toU.Record<K, V>builds an object type with one key for each member ofK.
type Direction = "up" | "down" | "left" | "right";
type Horizontal = Extract<Direction, "left" | "right">; // "left" | "right"
type Vertical = Exclude<Direction, Horizontal>; // "up" | "down"
const delta: Record<Direction, { dx: number; dy: number }> = {
up: { dx: 0, dy: -1 },
down: { dx: 0, dy: 1 },
left: { dx: -1, dy: 0 },
right: { dx: 1, dy: 0 },
};
function step(x: number, y: number, direction: Direction): [number, number] {
const { dx, dy } = delta[direction];
return [x + dx, y + dy];
}
console.log(step(0, 0, "left")); // [-1, 0]Record<Direction, ...> is a useful companion to a union. The object must have exactly one property per member. If you add "forward" to Direction, the delta object stops compiling until you add an entry for it. The compiler therefore tells you every lookup table that needs updating.
Where literal types get lost
The most frequent surprise is a value that you expect to be a literal but TypeScript infers as string. A later chapter covers the reasons in detail. Here are the two situations you will meet most often with unions.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(direction);
}
const a = "up";
move(a); // OK: const keeps the literal type "up"
let b = "up";
move(b); // Error: Argument of type 'string' is not assignable to parameter of type 'Direction'.
const options = { direction: "up" };
move(options.direction); // Error: the property is inferred as stringThere are two simple fixes. You can annotate the declaration (let b: Direction = "up"), or you can state the type of the object (const options: { direction: Direction } = { direction: "up" }). Annotating at the point where you create the value is usually clearer than casting later.
Avoid as Direction on values you did not check. A cast silences the compiler without proving anything:
type Direction = "up" | "down" | "left" | "right";
declare const input: string;
const unsafe = input as Direction; // compiles, but may hold any string at runtimeUnions exist only at compile time
A union of literals is erased when TypeScript compiles to JavaScript. At runtime, Direction does not exist. There is no object to loop over and no function to ask "is this string a valid direction?". This matters at trust boundaries: JSON from an API, form fields, URL parameters, and environment variables are all plain string at runtime, regardless of what your types say.
The usual solution is a type guard. It is a function whose return type, value is Direction, tells the compiler that a true result narrows the argument.
type Direction = "up" | "down" | "left" | "right";
function isDirection(value: string): value is Direction {
return (
value === "up" ||
value === "down" ||
value === "left" ||
value === "right"
);
}
function parseDirection(raw: string): Direction {
if (!isDirection(raw)) {
throw new Error(`Invalid direction: ${raw}`);
}
return raw; // narrowed to Direction
}
console.log(parseDirection("left")); // left
try {
parseDirection("sideways");
} catch (error) {
console.log((error as Error).message); // Invalid direction: sideways
}This guard repeats the list of values, so the type and the check can drift apart. Later chapters show how to derive the type from a runtime constant so there is one source of truth. That need is one reason enums exist, and it is central to the enum-versus-union decision in this tutorial.
Design guidance and limits
Unions of literals work well when:
- The set is small and stable, such as modes, directions, or status names.
- Values come from your own code, where the compiler checks them.
- You want values that are plain strings or numbers in JSON, logs, and APIs, with no import needed.
They have limits:
- Large unions slow down type checking and produce unreadable error messages. A union with hundreds of members is a sign to reconsider.
- A union cannot give a value a separate name. If
1means "Admin" and you want to writeRole.Adminin code, a bare1 | 2 | 3offers no names. Documentation comments on a type alias help only a little. - A union cannot be iterated at runtime, as explained above.
Common errors at a glance
| Symptom | Cause | Fix |
|---|---|---|
| `Argument of type 'string' is not assignable to parameter of type 'Direction'` | A `let` variable or object property was widened to `string` | Annotate the declaration, or use `const` |
| `This comparison appears to be unintentional` | The literal you compare with is not in the union | Fix the typo or update the union |
| `Type 'Movement' is not assignable to type 'Direction'` | You assigned a wider union to a narrower one | Narrow the value first, or widen the target type |
| Invalid value at runtime despite correct types | Data crossed a trust boundary as a plain `string` | Validate with a type guard |
| Missing property error on a `Record<Direction, ...>` object | A member was added to the union | Add an entry for the new member |
Putting it together
The next example combines the pieces from this chapter: a named union, a Record lookup, narrowing, and runtime validation.
type LogLevel = "debug" | "info" | "warn" | "error";
const severity: Record<LogLevel, number> = {
debug: 10,
info: 20,
warn: 30,
error: 40,
};
function isLogLevel(value: string): value is LogLevel {
return value in severity;
}
function shouldLog(configured: string, message: LogLevel): boolean {
const threshold: LogLevel = isLogLevel(configured) ? configured : "info";
return severity[message] >= severity[threshold];
}
console.log(shouldLog("warn", "error")); // true
console.log(shouldLog("warn", "info")); // false
console.log(shouldLog("verbose", "info")); // true (falls back to "info")Here isLogLevel reuses the keys of severity. Because severity is typed as Record<LogLevel, number>, it cannot be missing a level, so the guard matches the type for valid keys. One caveat remains: value in severity also returns true for inherited property names such as "toString". In production code, use Object.hasOwn(severity, value) (ES2022) instead.
Exercise
Given type Mode = "read" | "write" | "append";, write a type WriteMode that contains only "write" and "append" using a utility type. Then explain why let m = "read"; const x: Mode = m; fails but const m = "read"; const x: Mode = m; works.
Show answer
type WriteMode = Exclude<Mode, "read">; (or Extract<Mode, "write" | "append">). In the first snippet, let m = "read" is inferred as string because a let variable can be reassigned to any string, so string is not assignable to Mode. In the second, const m = "read" cannot change, so TypeScript keeps the literal type "read", which is a member of Mode.
Exercise
A function receives level: string from an environment variable and must pass it to log(level: LogLevel), where LogLevel is "debug" | "info" | "warn" | "error". Why is level as LogLevel a poor choice, and what should you write instead?
Show answer
The cast tells the compiler to trust the value without checking it, so a value such as "verbose" passes the compiler and causes a bug at runtime, because the union is erased and cannot check anything. Write a type guard such as function isLogLevel(v: string): v is LogLevel { return v === "debug" || v === "info" || v === "warn" || v === "error"; }, call it on the input, and handle the failure case by throwing an error or using a default.