Course contentsShow
← TypeScript
Lesson 1737 of 1,79639. TypeScript PerformanceFree lesson

Avoid Deeply Nested Conditional Types

Flatten or simplify nested conditional types that force excessive recursion during type resolution.

Avoid Deeply Nested Conditional Types

You'll learn: How to recognize when conditional type nesting harms compile performance, and techniques to flatten or simplify these types for faster resolution.


What's the Problem?

When you nest conditional types multiple levels deep—especially when combined with recursive patterns, union distribution, or multiple infer clauses—you force the TypeScript compiler to perform excessive recursion during type resolution. Each conditional layer adds another branch the compiler must evaluate, and when unions distribute through these conditionals, the complexity multiplies exponentially.

Think of it like nested if statements in runtime code: one or two levels are fine, but ten nested conditions become a maze that's hard to follow and slow to execute. The same principle applies at the type level, except the "execution" happens during compilation.


Signs You've Nested Too Deeply

  • Compilation becomes noticeably slower
  • IntelliSense feels sluggish in your editor
  • Type errors mention "excessively deep" or "possibly infinite"
  • Trace files show hot types with many instantiations
  • Simple type aliases take seconds to resolve

Flattening Strategies

1. Extract intermediate types: Instead of chaining conditionals inline, break them into named steps. This helps the type cache reuse intermediate results.

2. Use union extraction instead of nested branching: If you're filtering a union through multiple conditions, consider using a single-level conditional with union logic rather than nesting.

3. Replace deep conditionals with mapped types: Sometimes a mapped type with property conditionals is clearer and faster than deep conditional chains.

4. Limit recursion depth explicitly: If recursion is necessary, add a depth counter type parameter with a base case to prevent runaway evaluation.


When Complexity Is Worth It

Library authors building utility types might genuinely need sophisticated conditional logic. But for application code, simpler types with runtime validation often perform better and remain more maintainable.


Key Takeaway: Deeply nested conditional types create exponential compile-time cost. Flatten them by extracting intermediate types, using mapped types, or accepting slightly less precise types with better performance characteristics.