Sub topic 11
Limits and Pitfalls: Union Size, Recursion Depth, and Inference Behavior
This chapter assumes you know basic TypeScript types, unions, generics, conditional types, and mapped types. It focuses on cases where template literal types become difficult for the compiler or less precise than expected.
Template literal types are powerful because they can describe many strings at once. That power has costs. The compiler may need to create a large union, evaluate a recursive type many times, or choose an unexpected match when several patterns fit.
Union size can grow quickly
When a template literal type contains unions, TypeScript creates every possible combination.
type Color = "red" | "green" | "blue";
type Shade = "light" | "dark";
type ClassName = `${Shade}-${Color}`;
// "light-red" | "light-green" | "light-blue"
// | "dark-red" | "dark-green" | "dark-blue"The number of combinations is the product of the union sizes. Three colors and two shades create six members. Adding more parts multiplies the result:
type Variant = "solid" | "outline" | "ghost" | "link";
type Size = "sm" | "md" | "lg" | "xl";
type State = "default" | "hover" | "disabled";
type ButtonClass = `${Variant}-${Size}-${State}`;
// 4 × 4 × 3 = 48 possible stringsSmall unions are useful for editor completion and typo checking. Very large unions can slow compilation and may trigger an error such as “union type that is too complex to represent.”
| Situation | Typical result | Better choice |
|---|---|---|
| A few fixed values | Precise union | Use a template literal type |
| Many combinations | Slow or huge union | Keep some parts as `string` |
| External or user-provided text | Cannot enumerate safely | Validate at runtime |
A broad placeholder avoids expansion, but it also reduces precision:
type AnyButtonClass = `${string}-${string}-${string}`;This checks the general shape, but it accepts values such as "anything-at-all". Use it when exact enumeration is too expensive or the input comes from outside the program.
Recursive types have a depth limit
A recursive string type repeatedly applies a conditional type to a smaller part of the string.
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
type Parts = Split<"north/east/south", "/">;
// ["north", "east", "south"]This works because each recursive step removes a delimiter and moves toward the base case. A long string with many separators requires many instantiations. Complex recursive helpers can eventually produce “Type instantiation is excessively deep and possibly infinite.”
Use a clear base case and keep recursive work small. A recursion that does not reduce its input can also fail:
// Do not use a recursive type without a shrinking step.
// type Bad<S extends string> = S extends string ? Bad<S> : never;For deeply nested input, parse at runtime instead. TypeScript types are best for describing ordinary application data, not for processing arbitrarily large text.
Inference depends on the pattern
infer captures text that matches a template pattern. If a pattern has multiple possible matches, the result may not be what you intuitively expect.
type FirstPart<S extends string> =
S extends `${infer Head}-${infer Tail}` ? Head : S;
type Result = FirstPart<"one-two-three">;
// "one"The pattern captures the part before the first hyphen in this example. A different pattern can capture the remainder:
type LastPart<S extends string> =
S extends `${string}-${infer Last}` ? Last : S;
type Result = LastPart<"one-two-three">;
// "three"Inference becomes less precise when the input is string rather than a literal:
type RouteParam<S extends string> =
S extends `/${infer Param}` ? Param : never;
type Known = RouteParam<"/users">; // "users"
type Unknown = RouteParam<string>; // neverThe type string does not promise that a slash exists, so the conditional type cannot safely extract a parameter. Preserve literal types when you need this analysis:
const route = "/users" as const;
type Route = typeof route; // "/users"Without as const, a mutable string variable usually widens to string.
Choose the right level of precision
The following diagram shows the main trade-off.
A practical design often combines both approaches. Use template literal types for internal names such as event keys. Use a parser or validator for URLs, file paths, and user input.
type EventName<T extends string> = `on${Capitalize<T>}`;
type KnownEvent = EventName<"click" | "focus">;
// "onClick" | "onFocus"
function isKnownEvent(value: string): value is KnownEvent {
return value === "onClick" || value === "onFocus";
}
const input: string = "onClick";
if (isKnownEvent(input)) {
const event: KnownEvent = input;
console.log(event);
}The type assertion inside the type guard is justified by the runtime checks. A template literal type alone cannot inspect arbitrary runtime text.
Exercise
Why might ${Color}-${Size} be a poor choice when both Color and Size contain hundreds of members?
Show answer
The compiler must form every combination, which can create a huge union, slow compilation, or exceed its representation limits. Keep the type less specific or validate the value at runtime.