TypeScript
Type complexity
Learn the impact of type complexity on compile time.
What is type complexity?
Type complexity is the computational cost of resolving a type. TypeScript does extra work for each generic instantiation, union cross-product, and recursive expansion; this count is called the instantiation count. High counts directly slow compilation.
type Deep<N> = N extends 0
? unknown
: { next: Deep<N-1> };
// large N causes an instantiation explosion
Multiplying large unions (e.g. A × B × C) is the most common bottleneck.
Reducing complexity
There are three main ways to reduce type complexity: split large unions into groups, keep deep recursive types shallow, and avoid unnecessary generic instantiations. The instantiationCount usually concentrates around the most expensive type; simplifying it speeds up the whole build.
// bad: 10 × 10 × 10 = 1000
<A extends U1, B extends U2, C extends U3>
// good: single parameter, not nested
Tracing tools point to the most expensive type.
Exercise Count instantiations
Write a countInstantiations function that sums the params field of each type in a list. For Box(1), Pair(2), Triple(3), print the total.
Show example solution
function countInstantiations(types: { name: string; params: number }[]): number {
let instantiations = 0;
for (const t of types) {
instantiations += t.params;
}
return instantiations;
}
const types = [
{ name: "Box", params: 1 },
{ name: "Pair", params: 2 },
{ name: "Triple", params: 3 }
];
console.log(countInstantiations(types));
Test yourself
-
Which of the following meaningfully increases compile time?
- Adding comments to code
- Using semicolons
- Cross-product of large unions
- Using const instead of let
Show answer
Cross-product of large unions — Cross-products of large unions grow the instantiation count exponentially and seriously extend compile time; const, comments, and semicolons do not affect compile time.
-
Limit instantiations
type Box<T> = T extends string ? T : ____;
Show answer
type Box<T> = T extends string ? T : never;
-
Type complexity parts
- Instantiation count
- type resolution count
- Birleşim çarpımı
- source of exponential growth
- Derin özyineleme
- tree expansion cost
- Basitleştirme
- lowers cost
Next lesson: traceAnalyzer