Sub topic 3
Unions Expand into Every Combination
This chapter explains what TypeScript does when a template literal type has a union in a placeholder. It assumes you know string literal types, union types, and type aliases, and have read the previous chapter on basic template literal syntax. Generics and mapped types appear only briefly here and are covered in later chapters.
The working model: a cross product
A template literal type with no unions describes exactly one string. When a placeholder holds a union, TypeScript builds one string for every member of that union. When several placeholders hold unions, it builds one string for every possible choice across all of them. Mathematicians call this a cross product.
type Axis = "x" | "y";
type Direction = "start" | "end";
type Position = `${Axis}-${Direction}`;
// "x-start" | "x-end" | "y-start" | "y-end"Axis has 2 members and Direction has 2 members, so Position has 2 × 2 = 4 members. The result is an ordinary union of string literal types. After expansion, nothing in the type system remembers that it came from a template. You can use it anywhere you would use a hand-written union.
Using the expanded union
Because the result is a plain union, the usual tools work on it: function parameters, Record keys, and exhaustive checks.
type Axis = "x" | "y";
type Direction = "start" | "end";
type Position = `${Axis}-${Direction}`;
function align(position: Position): void {
console.log(`Aligning to ${position}`);
}
align("x-start");
// align("x-middle"); // Error: "x-middle" is not assignable to type Position
const offsets: Record<Position, number> = {
"x-start": 0,
"x-end": 100,
"y-start": 0,
"y-end": 50,
};
// Removing any one key above is a compile error, because Record<Position, number>
// requires all four.This is the main benefit. You write the two small unions once. The compiler keeps the combined list in sync. If you later add "center" to Direction, Position gains "x-center" and "y-center", and the offsets object fails to compile until you supply them.
How many members will you get?
The size of the result is the product of the sizes of the unions in the placeholders. Literal text between placeholders does not change the count.
| Template | Union sizes | Members in result | Column | Column | Column |
|---|---|---|---|---|---|
| `` `${"a" \ | "b"}-${1 \ | 2}` `` | 2 and 2 | 4 | |
| `` `${"a" \ | "b" \ | "c"}${"x" \ | "y"}` `` | 3 and 2 | 6 |
| `` `top-${"a" \ | "b"}` `` | 2 | 2 | ||
| `` `${Axis}-${Direction}-${Axis}` `` | 2, 2 and 2 | 8 |
Notice that the same alias can appear twice. The two uses are independent choices, so ` ${Axis}${Axis} gives "xx" | "xy" | "yx" | "yy", not just "xx" | "yy"`.
Placeholders are not limited to string literals. Number and boolean literal types are converted to their text form:
type Grid = `${1 | 2}x${3 | 4}`;
// "1x3" | "1x4" | "2x3" | "2x4"
type Flag = `enabled=${boolean}`;
// "enabled=true" | "enabled=false"boolean works because it is itself the union true | false. Enum types work in the same way: each member becomes a placeholder value.
Three or more unions
Nothing limits you to two placeholders. Each added union multiplies the result.
type Side = "top" | "bottom";
type Property = "margin" | "padding";
type Unit = "px" | "rem" | "em";
type Spacing = `${Property}-${Side}-${Unit}`;
// 2 * 2 * 3 = 12 members, for example "margin-top-px" and "padding-bottom-em"Combining with an open placeholder
If one placeholder is a union of literals and another is string, the union still expands, but each resulting member keeps an open ${string} part. The compiler does not try to list infinitely many strings.
type Color = "red" | "blue";
type ClassName = `${Color}-${string}`;
// `red-${string}` | `blue-${string}`
const a: ClassName = "red-large";
const b: ClassName = "blue-"; // allowed: ${string} may be empty
// const c: ClassName = "green-large"; // ErrorTwo details are worth remembering. First, ${string} matches the empty string, so "blue-" is valid. Second, the result has two members, not an unbounded number. Each member is a pattern type, which the compiler checks by matching text.
Intrinsic helpers also distribute
The built-in string types Uppercase, Lowercase, Capitalize, and Uncapitalize apply to every member of a union. The next chapter covers them in detail. They matter here because they combine naturally with expansion:
type EventName<T extends string> = `on${Capitalize<T>}`;
type AnyHandler = EventName<"click" | "focus" | "blur">;
// "onClick" | "onFocus" | "onBlur"This works without any conditional type. The union passed as T ends up inside the placeholder ${Capitalize<T>}, and the template literal type expands it. The distribution comes from the template literal type itself. It does not depend on the conditional-type distribution you may know from T extends U ? X : Y.
Edge cases
`never` makes everything disappear
A union with zero members is never. A cross product that includes a zero-member factor has zero members, so the whole template becomes never.
type Nothing = `prefix-${never}`; // never
type Keys<T> = `field-${keyof T & string}`;
type FromEmpty = Keys<{}>; // neverThis matters in generic code. If a mapped or inferred type produces never for a placeholder, you get never from the template, not an error. When a result is unexpectedly never, check each placeholder in turn.
Placeholders must be string-like
Only string, number, bigint, boolean, null, undefined, and their literal types (and unions of them) are allowed. An object type or symbol is rejected. A common case is keyof T, which is string | number | symbol in general. Intersect it with string to keep only the string keys, as in keyof T & string:
type Prefixed<T> = `get-${keyof T & string}`;
type P = Prefixed<{ name: string; age: number }>;
// "get-name" | "get-age"Without & string, the compiler reports that keyof T is not assignable to the allowed placeholder types.
A union with `string` collapses first
"a" | string is reduced to string before the template sees it. So ` ${"a" | string}-x becomes ${string}-x and stays an open pattern. Writing literals next to string` in one union does not give you a hint list in the template.
Order does not matter
A union has no meaningful order. Editor tooltips may list the members in a different order than you expect. Do not rely on the order for anything.
Where expansion starts to hurt
Each member of the result is a real type that the compiler must create and compare. Because the size is a product, it grows fast.
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
type D2 = `${Digit}${Digit}`; // 100 members
type D3 = `${Digit}${Digit}${Digit}`; // 1,000 members
// type D5 = `${Digit}${Digit}${Digit}${Digit}${Digit}`;
// Error TS2590: Expression produces a union type that is too complex to represent.The compiler refuses to build a union of 100,000 or more members from a single template expansion. The five-digit type is exactly that size, so it fails. Even well below the limit, large unions slow down type checking and editor responses, because every assignment against the union may compare against many members.
Common errors
- Expecting a pattern, getting a list. `
${Color}-${Size}is a finite list, so it rejects any value outside it. If you meant "any suffix", use${string}` for that part. - Forgetting
& stringonkeyof. The error mentionsstring | number | symboland is easy to misread. - Losing the literal type. A template expression only gets a template literal type when its context asks for one, for example a return type annotation or
as const. Otherwise it isstring.
type Axis = "x" | "y";
type Direction = "start" | "end";
type Position = `${Axis}-${Direction}`;
function makePosition(axis: Axis, direction: Direction): Position {
return `${axis}-${direction}`; // OK: the return type provides the context
}
function makeLoose(axis: Axis, direction: Direction) {
return `${axis}-${direction}`; // inferred return type is string
}
const p: Position = makeLoose("x", "end"); // Error: string is not assignable to PositionThe first function compiles because the annotated return type tells the compiler to build a template literal type from the expression. The second function infers plain string, which no longer fits Position. Annotate the return type, or write ` ${axis}-${direction} as const ` if you want the literal type.
Putting it together
A realistic use is permission names. Two small unions generate every valid permission string, and a lookup table must cover them all.
type Resource = "user" | "post" | "comment";
type Action = "create" | "read" | "update" | "delete";
type Permission = `${Resource}:${Action}`; // 12 members
const granted: Record<Permission, boolean> = {
"user:create": false,
"user:read": true,
"user:update": false,
"user:delete": false,
"post:create": true,
"post:read": true,
"post:update": true,
"post:delete": false,
"comment:create": true,
"comment:read": true,
"comment:update": false,
"comment:delete": false,
};
function can(permission: Permission): boolean {
return granted[permission];
}
console.log(can("post:update")); // trueAdding "archive" to Action immediately produces three new required keys in granted, one for each resource. The compiler reports the missing keys, so no permission can be forgotten.
Summary of the model
- A placeholder with a union produces one result per member.
- Several placeholders multiply: the count is the product of the union sizes.
- Literal text between placeholders never changes the count.
- A
neverplaceholder makes the whole templatenever. - An open
${string}or${number}part stays as a pattern and does not expand. - Around 100,000 members, the compiler stops with error TS2590.
Exercise
How many members does ` ${"a" | "b" | "c"}-${1 | 2}-${"x" | "y"} ` have, and what is the first member if you list them with the leftmost union varying slowest?
Show answer
It has 3 × 2 × 2 = 12 members. The first member is "a-1-x". The full set is every choice of letter from a, b, c, number from 1, 2, and letter from x, y joined by hyphens.
Exercise
What is the type of Result below, and why?
type Id = "user" | "post";
type Result = ${Id}-${never};
Show answer
Result is never. The placeholder never is a union with zero members, so the cross product has zero members. Any template that contains a never placeholder collapses to never.
Exercise
Write a type Margin that accepts exactly the strings "margin-top", "margin-right", "margin-bottom", and "margin-left", using one template literal type and one union alias. Then explain why ` margin-${string} ` would be a worse choice if you want typos rejected.
Show answer
type Side = "top" | "right" | "bottom" | "left";
type Margin = margin-${Side};
With ` margin-${string} ` the placeholder matches any text, so "margin-topp" would be accepted. The union alias gives a finite list, so a typo is a compile error.