0
0
Typescriptprogramming~5 mins

Non-distributive conditional types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Non-distributive conditional types
O(1)
Understanding Time Complexity

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

Specifically, how does TypeScript handle conditional checks when the input is a union type but the condition is made non-distributive?

Scenario Under Consideration

Analyze the time complexity of this TypeScript code snippet.


type NonDistributive = [T] extends [string | number] ? true : false;

// Example usage:
type Test1 = NonDistributive;
type Test2 = NonDistributive;

This code checks if a type T is assignable to string or number without distributing over unions.

Identify Repeating Operations

Look for repeated checks or evaluations inside the conditional type.

  • Primary operation: TypeScript evaluates the conditional once on the whole type wrapped in a tuple to prevent distribution.
  • How many times: Exactly once, regardless of how many union members T has.
How Execution Grows With Input

Since the conditional is non-distributive, the check happens once no matter how many types are in the union.

Input Size (n)Approx. Operations
1 (e.g., string)1
2 (e.g., string | number)1
10 (e.g., union of 10 types)1

Pattern observation: The number of operations stays the same even if the union grows larger.

Final Time Complexity

Time Complexity: O(1)

This means the evaluation time does not increase as the input type union grows.

Common Mistake

[X] Wrong: "The conditional type runs once for each member of the union, so time grows with union size."

[OK] Correct: Wrapping the type in a tuple disables distribution, so the check happens only once on the whole union.

Interview Connect

Understanding how TypeScript handles conditional types helps you write efficient type checks and reason about compiler performance in real projects.

Self-Check

What if we removed the tuple wrapping and let the conditional distribute over the union? How would the time complexity change?