Sub topic 11
Limits and pitfalls: union size, recursion depth, and inference behavior
This chapter assumes you can write template literal types with union placeholders and infer. It also assumes you know mapped types and recursive conditional types. Here you learn where those tools break down: the compiler refuses a type, slows down, or accepts strings you did not mean to allow.
Union size: the cross product explodes
When a template literal type has several union placeholders, TypeScript builds every combination. The number of members is the product of the sizes of each union.
A design system with 3 properties, 4 sides, and 8 spacing steps produces 3 × 4 × 8 = 96 strings. That is fine. Add one more union of 10 values and you have 960. The growth is multiplicative, so a few extra placeholders can push a type past what the compiler allows.
TypeScript caps these unions. If a template literal type would produce 100,000 or more members, you get error TS2590, "Expression produces a union type that is too complex to represent."
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
type Two = `${Digit}${Digit}`; // 100 members
type Four = `${Two}${Two}`; // 10,000 members
type Six = `${Four}${Digit}${Digit}`; // 1,000,000 members
// Error: Expression produces a union type that is too complex to represent.Smaller unions also cost you. Every member is a separate type that the compiler must create, compare, and keep in memory. A union of 10,000 strings can make autocomplete and error messages slow even though it stays under the cap.
Fixes for large unions
You have three main options.
- Use a broader placeholder such as
${number}or${string}instead of listing every value. - Split the type so that only the part that matters is enumerated. For example, enumerate the property names and let the value be
${number}px. - Validate at runtime and use a branded string type for the result.
type SixDigits = string & { readonly __brand: "SixDigits" };
function parseSixDigits(input: string): SixDigits {
if (!/^\d{6}$/.test(input)) {
throw new Error(`Expected six digits, got "${input}"`);
}
return input as SixDigits;
}
const pin = parseSixDigits("123456");The brand does not prove the string is six digits at compile time. It records that your function checked it. That is a different guarantee from a template literal type, and it is the one you can afford here.
Imprecision: placeholders accept more than you expect
A placeholder describes a family of strings. The family is often wider than the mental picture you have of it.
type Px = `${number}px`;
const a: Px = "1e3px"; // accepted: "1e3" is a valid numeric literal
const b: Px = "0x10px"; // accepted: hexadecimal is numeric too
type OnEvent = `on${string}`;
const c: OnEvent = "on"; // accepted: ${string} can be empty${number} accepts any string that parses as a finite number, including exponent and hexadecimal forms. It does not check ranges, integer-ness, or sign. ${string} matches the empty string, so on${string} includes plain "on".
If you need a stricter shape, there are two choices:
- Enumerate a small set of allowed pieces, as long as the union stays small.
- Accept the loose type at the boundary and add a runtime check.
Widening: template expressions are often just `string`
A template literal type describes a type. A template expression in a value position does not always get one.
type Id = `id-${number}`;
const n = 5;
const plain = `id-${n}`; // type: string
const exact = `id-${n}` as const; // type: "id-5"
function load(id: Id) {
return id;
}
load(`id-${n}`); // OK: the parameter type gives the expression a contextWithout as const or a contextual type, TypeScript widens the result to string. When a function that expects a template literal type rejects a string you built, check whether the expression was widened.
Recursion depth
Recursive conditional types are how you split and parse strings. The compiler limits how deep they may go, and the limit depends on the shape of the recursion.
- A recursive type whose recursive call is wrapped in something else, like a tuple spread, is not tail recursive. The compiler gives up after roughly 50 levels with error TS2589, "Type instantiation is excessively deep and possibly infinite."
- A recursive type whose recursive call is the entire result of the branch is tail recursive. Since TypeScript 4.5, the compiler evaluates these in a loop and allows about 1,000 levels.
The Split type from earlier in this tutorial is not tail recursive. The spread [Head, ...Split<Tail, D>] wraps the recursive call:
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];It works for short inputs. A string with many dozens of segments can trigger TS2589.
To make it tail recursive, carry the result in an accumulator parameter. The recursive call then appears alone in the branch.
type SplitAcc<
S extends string,
D extends string,
Acc extends string[] = [],
> = S extends `${infer Head}${D}${infer Tail}`
? SplitAcc<Tail, D, [...Acc, Head]>
: [...Acc, S];
type Parts = SplitAcc<"a-b-c", "-">; // ["a", "b", "c"]The same technique works for splitting a string into characters:
type Chars<S extends string, Acc extends string[] = []> =
S extends `${infer C}${infer Rest}` ? Chars<Rest, [...Acc, C]> : Acc;
type Letters = Chars<"type">; // ["t", "y", "p", "e"]Edge case: an empty delimiter
With D set to "", the pattern ${infer Head}${D}${infer Tail} takes one character as Head. The recursion continues until S is empty, and the empty string no longer matches, so it lands in the fallback branch. The result has a trailing empty string.
type Odd = SplitAcc<"abc", "">; // ["a", "b", "c", ""]Use Chars when you want characters, or constrain D so it cannot be empty.
Instantiation cost
Even under the depth limit, deep recursion on long strings is slow. Each step creates new types. Two habits keep this manageable:
- Parse only the part of the string you need, and stop early.
- Avoid running a recursive type on user-supplied or very long string types, such as a whole HTML document written as a literal.
Inference behavior
infer inside a template literal follows fixed matching rules. Most surprises come from forgetting them.
Earlier placeholders are shortest, the last takes the rest
Each infer before a literal separator captures the shortest piece that lets the match succeed. The final infer takes everything that remains.
type First<S extends string> =
S extends `${infer A}-${infer B}` ? [A, B] : never;
type R1 = First<"a-b-c">; // ["a", "b-c"]
type R2 = First<string>; // never
type R3 = First<"a-b" | "c-d-e">; // ["a", "b"] | ["c", "d-e"]Three things appear here:
Astops at the first-, andBkeeps"b-c".- A plain
stringhas no literal structure to match, so the conditional is false and you get the fallback. - A bare type parameter in a conditional type distributes over unions, so each member of a union is matched on its own.
Two infer placeholders next to each other with no separator behave differently. The first captures a single character and the second takes the rest. That is how Chars works.
Non-literal input silently falls through
A route parser written for literal strings returns never when it is given string. Nothing fails loudly. The result is just empty.
type ExtractRouteParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? Param | ExtractRouteParams<`/${Rest}`>
: T extends `${string}:${infer Param}`
? Param
: never;
type SafeParams<T extends string> = string extends T
? Record<string, string>
: { [K in ExtractRouteParams<T>]: string };
type A = SafeParams<"/users/:id/posts/:postId">; // { id: string; postId: string }
type B = SafeParams<string>; // Record<string, string>The check string extends T is true only when T is the wide string type. It lets you fall back to a loose type instead of an unusable empty one.
Converting a string type to a number type
Since TypeScript 4.8, infer N extends number can parse a numeric string into a numeric literal type:
type ToNumber<S extends string> =
S extends `${infer N extends number}` ? N : never;
type Answer = ToNumber<"42">; // 42This only produces a literal when the text round-trips cleanly, meaning converting the number back gives the same string. Test odd inputs such as "4.0" or "1e3" in your own project before depending on the result.
When the compiler pushes back
| Symptom | Likely cause | Fix |
|---|---|---|
| TS2590 on a type alias | Cross product of unions reached 100,000 members | Use a broader placeholder, split the type, or brand a validated string |
| TS2589 on a recursive type | Non-tail recursion beyond about 50 levels | Add an accumulator so the call is in tail position |
| Editor is slow, no error | Large unions or deep recursion on long strings | Parse less, enumerate less, and measure |
| A bad string is accepted | `${number}` or `${string}` is broader than expected | Narrow the pieces or add a runtime check |
| Result is `never` for a `string` input | The pattern cannot match a non-literal type | Guard with `string extends T` |
| Template expression typed as `string` | Widening of the value expression | Use `as const` or give it a contextual type |
Measuring instead of guessing
Two compiler flags tell you where the time goes:
tsc --noEmit --extendedDiagnostics
tsc --noEmit --generateTrace ./trace--extendedDiagnostics prints counts such as instantiations and type count. If those numbers jump after you add a type, that type is the cost. --generateTrace writes a trace folder that you can open in a Chromium-based browser's performance tooling, such as the chrome://tracing page, to see which expressions took the longest.
Deciding whether a template literal type is worth it
A template literal type earns its place when it catches real mistakes at a call site, such as a misspelled event name or an unknown route parameter. It does not earn its place when it exists to prove a runtime format. Use these criteria:
- Is the set of valid strings small enough to enumerate, or does it have a simple prefix, suffix, or separator structure?
- Does the error message the compiler shows help the person who made the mistake?
- Would a runtime check plus a branded type give the same safety with less compile-time cost?
When the answer to the third question is yes, prefer the runtime check.
Exercises
Exercise
A teammate defines type Hex = "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"|"a"|"b"|"c"|"d"|"e"|"f" and then type Color = #${Hex}${Hex}${Hex}${Hex}${Hex}${Hex}``. The compiler reports TS2590. Explain why, and give one way to fix it.
Show answer
The type has six placeholders of 16 members each, so it expands to 16^6 = 16,777,216 members. That is far over the 100,000 limit. One fix is to use the looser type #${string} and validate the format at runtime, returning a branded HexColor type from the validating function. Another is to keep the literal type loose and enumerate only a small set of named colors.
Exercise
This type fails with TS2589 on a string with 80 segments. Rewrite it so the recursion is in tail position.
type Join<T extends string[], D extends string> =
T extends [infer First extends string, ...infer Rest extends string[]]
? Rest extends []
? First
: ${First}${D}${Join<Rest, D>}
: "";
Show answer
The recursive call is wrapped inside a template literal, so it is not in tail position. Carry the output in an accumulator:
type Join<T extends string[], D extends string, Acc extends string = ""> =
T extends [infer First extends string, ...infer Rest extends string[]]
? Join<Rest, D, Acc extends "" ? First : ${Acc}${D}${First}>
: Acc;
The recursive call is now the entire result of the branch, so the compiler evaluates it in a loop and allows about 1,000 levels. One side effect: an empty first element is treated like an empty accumulator, so a leading empty string is dropped.