The Type Cache and Memoization
What you'll learn: How TypeScript caches type computations to avoid redundant inference work.
The Core Idea
When TypeScript checks your code, it performs countless type computations—resolving generics, checking structural compatibility, narrowing unions, and more. Doing this work repeatedly for the same types would be incredibly wasteful.
To optimize performance, TypeScript uses type caching and memoization. When the compiler computes a type relationship or resolves a complex type expression, it stores the result. If it encounters that exact computation again during the same compilation, it retrieves the cached answer instead of recalculating.
Think of it like a mathematician who writes down solved equations in a notebook. Once they've proven that 2 + 2 = 4, they don't re-add the numbers every time—they just look up the answer.
How It Works in Practice
TypeScript maintains internal caches for:
- Type identity checks: Whether two types are identical
- Assignability relationships: Whether type A is assignable to type B
- Generic instantiations: The result of applying type arguments to generic types
- Conditional type resolutions: The outcome of
T extends U ? X : Yexpressions - Mapped type transformations: Results of mapped type operations
When you have deeply nested generics or recursive conditional types, this memoization can be the difference between instant type-checking and multi-second delays (or even hitting TypeScript's recursion limits).
The cache is scoped to a single compilation run. When you save a file and trigger a recompilation, TypeScript rebuilds its cache from scratch—though incremental compilation (with .tsbuildinfo) preserves some information across runs.
Key Takeaway: TypeScript memoizes type computations to avoid redundant work, making complex type operations feasible by caching previously resolved type relationships and transformations.