Sub topic 9
Recognizing expensive types and excessive instantiation
This chapter assumes you have read the earlier chapters on --extendedDiagnostics and on generating and analyzing a trace. You should be comfortable with generics, conditional types, mapped types, and union types. The goal is to look at a type and judge, before you measure, whether the checker will find it expensive. You will also learn to recognize the two errors the compiler raises when a type becomes too expensive.
What "expensive" means to the checker
The checker does not evaluate types the way a program runs code. It builds type objects and caches them. Cost comes from three sources:
- Instantiation. Replacing type parameters with concrete types creates a new type object.
Array<string>is an instantiation ofArray<T>. Every distinct set of arguments makes a new object, and each object must be created, interned, and often compared. - Relation checks. Deciding whether type
Ais assignable to typeBcan mean walking every member of both. Results are cached per pair of type IDs, so a large number of distinct types defeats the cache. - Normalization. Unions are deduplicated and sorted, and intersections are distributed over unions. Both operations grow quickly with input size.
The Instantiations and Types counters in --extendedDiagnostics output are the cheapest early signal. A project with a modest number of files but millions of instantiations has an expensive type pattern somewhere. A project with many files and few instantiations has a scope problem, which an earlier chapter covered.
Patterns that tend to be expensive
| Pattern | Why it costs | Typical symptom |
|---|---|---|
| Recursive conditional types | Each level instantiates the next. Non-tail-recursive forms are limited to a depth of about 100. | TS2589 |
| Template literal types over several unions | Members multiply: 10 × 10 × 10 × 10 × 10 × 10 is 1,000,000. | TS2590 or a very slow check |
| Large unions compared with each other | Assignability compares members pairwise. | Slow `checkExpression` events |
| Large intersections of object types | Properties are resolved by merging every constituent, and the merge is repeated at each use. | Slow when the type is used as a parameter or return type |
| Mapped types over large key sets | One property is produced per key, and each is instantiated. | High `Types` count |
| Generic functions with many overloads or deep inference | Each candidate signature is tried and inferred. | Hot spots at call sites, not at declarations |
| Unannotated exported functions returning big inferred types | The type must be inferred, then printed for declaration files. | Slow `checkSourceFile` on library entry points |
None of these is wrong to use. They become a problem when they are large, nested, or reached from many places.
Excessive depth: TS2589
TS2589 reads "Type instantiation is excessively deep and possibly infinite." The checker tracks how many instantiations are nested at one time. When the depth reaches 100 (or the total count for one expression reaches 5,000,000), it stops. It reports the error and treats the result as an error type, which behaves like any.
Tail-recursive conditional types get a larger budget of about 1,000 levels, because the checker can loop instead of nest. A recursive call that is wrapped in something else, such as a spread into a new tuple, is not in tail position.
This file shows both forms:
// Tail-recursive: the recursive call is the whole branch result.
type Tuple<N extends number, T extends unknown[] = []> =
T["length"] extends N ? T : Tuple<N, [...T, 0]>;
// Not tail-recursive: the recursive call is wrapped in a tuple spread.
type Reverse<T extends unknown[]> =
T extends [infer Head, ...infer Rest] ? [...Reverse<Rest>, Head] : [];
type Small = Reverse<Tuple<10>>; // fine
// On current compilers this is expected to report TS2589,
// because Reverse nests once per element.
type TooDeep = Reverse<Tuple<500>>;The second type fails while the first, much longer, build succeeds. That difference is the thing to look for when reading a recursive type.
The error does not always point at the recursive type itself. It points at the place where the instantiation was triggered, which may be a call site in application code that passes a type argument to a library function. When you see TS2589 in your own file, look at the declaration of the generic being called, not only at the line the editor underlines.
Unions that are too complex: TS2590
TS2590 reads "Expression produces a union type that is too complex to represent." The checker caps a union at 100,000 constituents. It reaches that cap mostly through cross products, from template literal types or from distributing intersections over unions.
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
// 10 * 10 * 10 = 1,000 members: fine.
type Code3 = `${Digit}${Digit}${Digit}`;
// 10^6 = 1,000,000 members: exceeds the union limit, so TS2590.
type Code6 = `${Digit}${Digit}${Digit}${Digit}${Digit}${Digit}`;Long before the hard limit, a union with thousands of members slows every assignment that involves it. The usual real-world cause is a union built from a product of string literals, such as ${Resource}:${Action}:${Scope}, used for permissions, event names, or CSS class names. The three input unions look small, but their product is not.
The shape of the work: how instantiation spreads
One generic type often fans out into many instantiations, and those can fan out again:
Two things follow from this picture. A loop back to the instantiation step is what makes recursion expensive, and the depth limit is the safety valve on that loop. Also, the cache at the relation step only helps when the same two types are compared again. A pattern that creates a fresh type for each call defeats the cache and repeats the pairwise comparison each time.
Spotting expensive types in a measurement
Start with the baseline. Run the diagnostics on the full project and note Instantiations, Types, and Check time:
npx tsc --noEmit --extendedDiagnostics | grep -E "Instantiations|Types|Check time"To find which file or expression is responsible, generate a trace and analyze it as in the previous chapters. The analyzer output lists hot spots. In each one, look at the following:
- The event name.
checkSourceFileis the whole file.checkExpressionandcheckVariableDeclarationare narrower and usually more useful, because they name a position inside the file. - The path and position. Open the file at that offset. The expression is often a call to a generic function, not a type declaration.
- The type IDs mentioned in the event. Search
types.jsonfor those IDs. An entry with a longdisplaystring, manyunionTypes, or arecursionIdshared by thousands of other entries tells you what is being built.
Counting entries per recursionId is a quick way to find a runaway recursive type. This script assumes you have a traceDir from --generateTrace:
import { readFileSync } from "node:fs";
interface TypeEntry {
id: number;
recursionId?: number;
symbolName?: string;
display?: string;
}
const types: TypeEntry[] = JSON.parse(
readFileSync("traceDir/types.json", "utf8"),
);
const byRecursion = new Map<number, TypeEntry[]>();
for (const t of types) {
if (t.recursionId === undefined) continue;
const group = byRecursion.get(t.recursionId) ?? [];
group.push(t);
byRecursion.set(t.recursionId, group);
}
const top = [...byRecursion.entries()]
.sort((a, b) => b[1].length - a[1].length)
.slice(0, 5);
for (const [recursionId, group] of top) {
const sample = group[0];
console.log(
`recursionId ${recursionId}: ${group.length} types, e.g. ${sample.symbolName ?? sample.display ?? "?"}`,
);
}Run it with a tool that executes TypeScript, such as npx tsx script.ts. A group with thousands of entries is a candidate. Whether it is a real problem depends on how much check time the trace attributes to it.
Isolating a suspect type
Once you have a candidate, reproduce it in a small file so that the measurement is not mixed with the rest of the project:
npx tsc --noEmit --extendedDiagnostics --strict --target es2022 suspect.tsPassing a file on the command line makes tsc ignore tsconfig.json, which is why the options are given explicitly. Compare Instantiations and Check time for a version that uses the suspect type and one that replaces it with a simple placeholder such as unknown. The difference is the cost of the type. If it is small, the problem lies elsewhere, and you saved yourself a rewrite.
Common mistakes when judging cost
- Blaming the declaration, not its uses. A moderately costly type used in 2,000 places costs 2,000 times as much. The trace shows the uses, and the fix may be to name or annotate at the use sites.
- Treating the TS2589 location as the root cause. As described above, the error appears where the instantiation began.
- Confusing the editor with the compiler. A hot spot that appears only in tsserver, and not in
tsc, points to editor-specific work. That is the subject of a later chapter. - Optimizing without a before and after. Intuition about which type is expensive is often wrong. Record
InstantiationsandCheck timefirst. - Raising limits. The depth and union limits are fixed in the compiler and cannot be changed through
tsconfig.json. The only remedy is to change the types.
What to do next
Recognizing a pattern is the diagnostic half. The next chapter covers the rewrites: replacing intersections with interfaces, naming intermediate types, annotating exported functions, and restructuring recursive conditional types. For now, the output of this chapter is a short list of suspect types, each with a measured cost, ready to be rewritten and re-measured.
Exercise
A project reports TS2589 on a call to deepMerge(a, b) in app.ts. The generic DeepMerge<A, B> that deepMerge returns is declared in lib/merge.d.ts, and its recursive call is [...DeepMerge<Rest, B>, Head]. Where should you look first, why does the recursion hit the limit, and why is @ts-ignore a poor fix?
Show answer
Look at DeepMerge in lib/merge.d.ts, because the error is reported where the instantiation started (the call in app.ts), not where the type is defined. The recursive call is wrapped in a tuple spread, so it is not in tail position. Each element nests another level, and the depth limit of about 100 is reached for large inputs. @ts-ignore hides the message but the checker still does the work up to the limit, and the result type becomes any, so you lose type safety and keep the cost.
Exercise
A permission type is defined as ${Resource}:${Action}:${Scope} where Resource has 40 members, Action has 30, and Scope has 100. What happens, and how would you confirm the cost with measurements before changing it?
Show answer
The product is 40 × 30 × 100 = 120,000 members, which is above the 100,000 union limit, so the compiler reports TS2590. To confirm, run tsc --noEmit --extendedDiagnostics and record Instantiations, Types, and Check time. Then reproduce the type in a small file and compare it with a version that uses string. If you have a trace, find the matching checkExpression events and the large union entry in types.json.