Nested conditional types in Typescript - Time & Space Complexity
We want to understand how the time it takes to evaluate nested conditional types grows as the input type changes.
Specifically, how does the complexity increase when conditions are inside other conditions?
Analyze the time complexity of the following TypeScript nested conditional type.
type NestedCheck = T extends string
? T extends "hello"
? true
: false
: false;
This type checks if T is a string, and if so, checks if it is exactly "hello".
Look for repeated checks or evaluations inside the type.
- Primary operation: Conditional type checks nested inside another conditional.
- How many times: Each check happens once per type evaluation, but nested checks depend on the outer condition.
As the input type changes, the nested checks happen only if the outer condition is true.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 (simple type) | 2 checks (outer + inner) |
| 10 (union of types) | Up to 20 checks (each type checked twice) |
| 100 (larger union) | Up to 200 checks |
Pattern observation: The number of checks grows linearly with the number of types in the input.
Time Complexity: O(n)
This means the time to evaluate grows directly in proportion to the number of types being checked.
[X] Wrong: "Nested conditional types multiply the time exponentially."
[OK] Correct: Each nested check only happens if the outer condition passes, so the total checks add up linearly, not multiply exponentially.
Understanding how nested conditional types scale helps you write efficient type logic and explain your reasoning clearly in interviews.
"What if the nested conditional type had multiple layers instead of just two? How would the time complexity change?"