CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

index.ts
// türlerin parametre sayısını topla
// her tür için params alanını ekle
// toplamı döndür
// sonucu yazdır

Sample solution

index.ts
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));

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which of the following meaningfully increases compile time?

  • Adding comments to code
  • Using semicolons
  • Cross-product of large unions Correct answer
  • Using const instead of let

Explanation: Cross-products of large unions grow the instantiation count exponentially and seriously extend compile time; const, comments, and semicolons do not affect compile time.

2 Limit instantiations

Question
type Box<T> = T extends string ? T : ____;
Answer
type Box<T> = T extends string ? T : never;

Explanation: To cut unnecessary instantiation use never; any disables checking, unknown keeps expanding, and object means something different.

3 Type complexity parts

Term Meaning
Instantiation count type resolution count
Birleşim çarpımı source of exponential growth
Derin özyineleme tree expansion cost
Basitleştirme lowers cost

All lessons in Expert