0
0
Typescriptprogramming~5 mins

Nested conditional types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested conditional types
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify Repeating Operations

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.
How Execution Grows With Input

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.

Final Time Complexity

Time Complexity: O(n)

This means the time to evaluate grows directly in proportion to the number of types being checked.

Common Mistake

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

Interview Connect

Understanding how nested conditional types scale helps you write efficient type logic and explain your reasoning clearly in interviews.

Self-Check

"What if the nested conditional type had multiple layers instead of just two? How would the time complexity change?"