Sub topic 3
Unions Expand into Every Combination
Prerequisites
Assume you know basic TypeScript type aliases, string literal types, union types, and generic type parameters. A union type such as "red" | "blue" means that a value may be one of several exact strings.
A template literal type builds string literal types with the same ${...} shape used by JavaScript template strings. When a placeholder contains a union, TypeScript combines every member of that union with every other placeholder.
The Cartesian product
Start with two unions:
type Color = "red" | "blue";
type Size = "sm" | "lg";Use them as placeholders:
type ClassName = `${Color}-${Size}`;ClassName is equivalent to this union:
type ClassName =
| "red-sm"
| "red-lg"
| "blue-sm"
| "blue-lg";TypeScript produces one result for each possible combination. The two Color members combine with the two Size members, producing four strings.
const first: ClassName = "red-sm";
const second: ClassName = "blue-lg";
// const invalid: ClassName = "green-md";
// Error: Type '"green-md"' is not assignable to type 'ClassName'.The resulting type is still a union of string literal types. It does not create a runtime value or transform strings while the program runs.
| `Color` | `Size` | Result |
|---|---|---|
| `"red"` | `"sm"` | `"red-sm"` |
| `"red"` | `"lg"` | `"red-lg"` |
| `"blue"` | `"sm"` | `"blue-sm"` |
| `"blue"` | `"lg"` | `"blue-lg"` |
More than two placeholders
Each additional union multiplies the number of possible results:
type Scheme = "light" | "dark";
type Control = "button" | "input";
type TestId = `${Scheme}-${Control}-${Size}`;TestId contains eight combinations:
type TestId =
| "light-button-sm"
| "light-button-lg"
| "light-input-sm"
| "light-input-lg"
| "dark-button-sm"
| "dark-button-lg"
| "dark-input-sm"
| "dark-input-lg";The number of combinations is the product of the union sizes. In this example, there are two schemes, two controls, and two sizes:
2 × 2 × 2 = 8This behavior is sometimes called a cross product or Cartesian product. You can visualize the process as a tree:
Combining literal parts and unions
Literal text around a placeholder becomes part of every result:
type ApiVersion = "v1" | "v2";
type Resource = "users" | "posts";
type Endpoint = `/api/${ApiVersion}/${Resource}`;This produces:
type Endpoint =
| "/api/v1/users"
| "/api/v1/posts"
| "/api/v2/users"
| "/api/v2/posts";You can use this to constrain configuration values:
function request(endpoint: Endpoint) {
console.log(`Requesting ${endpoint}`);
}
request("/api/v1/users");
request("/api/v2/posts");
// request("/api/v3/users");
// Error: the endpoint is not part of Endpoint.The function receives an ordinary string at runtime, but callers must provide one of the known endpoint strings at compile time.
The effect of broad types
A broad string placeholder behaves differently:
type Greeting = `Hello, ${string}`;
const known: Greeting = "Hello, Ada";
const another: Greeting = "Hello, anyone";
// const wrong: Greeting = "Hi, Ada";
// Error: the string does not start with "Hello, ".Because string contains infinitely many possible strings, TypeScript cannot enumerate the complete union. Instead, it keeps the pattern as a template literal type. A finite union gives precise enumeration; a broad primitive gives a pattern with less detail.
The same principle applies to other primitive placeholders:
type PixelLength = `${number}px`;
const width: PixelLength = "12px";
const fraction: PixelLength = "1.5px";
// const invalid: PixelLength = "wide";
// Error: "wide" is not a numeric string followed by "px".Common errors
A common mistake is expecting placeholders to preserve combinations that are meaningful in the domain. TypeScript mechanically creates every combination:
type Platform = "ios" | "android";
type Architecture = "arm64" | "x64";
type Build = `${Platform}-${Architecture}`;This type allows all four combinations, even if a real build system supports only some of them. If the valid combinations are unrelated, write the union explicitly or model each valid object as a separate union member.
Another issue is size. If three placeholders each contain ten members, the result may contain up to 1,000 combinations. Large generated unions can make checking and editor suggestions slower.
Exercise
What string literals are included in ${"get" | "set"}-${"name" | "age"}?
Show answer
"get-name" | "get-age" | "set-name" | "set-age".