Distributive conditional types in Typescript - Time & Space 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?
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.
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.
Each union member is checked separately, so the work grows as the number of members grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 conditional checks |
| 10 | 10 conditional checks |
| 100 | 100 conditional checks |
Pattern observation: The number of checks grows directly with the number of union members.
Time Complexity: O(n)
This means the time to evaluate grows linearly with the number of union members.
[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.
Understanding how TypeScript processes distributive conditional types helps you reason about type performance and complexity in real projects.
"What if we changed the conditional type to not distribute over unions? How would the time complexity change?"