0
0
Typescriptprogramming~5 mins

Distributive conditional types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Distributive conditional types
O(n)
Understanding Time Complexity

We want to understand how the time it takes to evaluate distributive conditional types changes as the input type grows.

Specifically, how does TypeScript handle conditional checks on union types?

Scenario Under Consideration

Analyze the time complexity of the following TypeScript distributive conditional type.


type FilterString = T extends string ? T : never;

// Example usage:
type Result = FilterString<'a' | 1 | 'b' | boolean>;

This type checks each member of a union and keeps only the string members.

Identify Repeating Operations

Look for repeated checks or operations in the type evaluation.

  • Primary operation: Conditional check on each union member.
  • How many times: Once per member in the union type.
How Execution Grows With Input

Each union member is checked separately, so the work grows as the number of members grows.

Input Size (n)Approx. Operations
33 conditional checks
1010 conditional checks
100100 conditional checks

Pattern observation: The number of checks grows directly with the number of union members.

Final Time Complexity

Time Complexity: O(n)

This means the time to evaluate grows linearly with the number of union members.

Common Mistake

[X] Wrong: "The conditional type runs once for the whole union at once."

[OK] Correct: TypeScript actually distributes the conditional over each union member separately, so it runs multiple times.

Interview Connect

Understanding how TypeScript processes distributive conditional types helps you reason about type performance and complexity in real projects.

Self-Check

"What if we changed the conditional type to not distribute over unions? How would the time complexity change?"