Conditional types for overload replacement in Typescript - Time & Space Complexity
We want to understand how using conditional types instead of overloads affects the time it takes for TypeScript to process code.
Specifically, how does the complexity grow as the input types or conditions increase?
Analyze the time complexity of the following TypeScript conditional type used to replace function overloads.
type Result = T extends string ? number : boolean;
function example(arg: T): Result {
if (typeof arg === 'string') {
return arg.length as Result;
} else {
return (arg !== null) as Result;
}
}
This code uses a conditional type to decide the return type based on the input type instead of multiple overloads.
Look at what TypeScript does when checking this code.
- Primary operation: TypeScript evaluates the conditional type
Result<T>for each usage. - How many times: Once per unique type
Tencountered during compilation.
As the number of different input types T grows, TypeScript must evaluate the conditional type for each.
| Input Types Count (n) | Approx. Evaluations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows linearly with the number of unique input types.
Time Complexity: O(n)
This means the time to process grows directly in proportion to how many different input types are used.
[X] Wrong: "Conditional types run once and don't add to compile time as inputs grow."
[OK] Correct: Each unique input type triggers a new evaluation, so more inputs mean more work.
Understanding how conditional types scale helps you write efficient type code and shows you think about performance beyond runtime.
What if we replaced the conditional type with multiple overloads? How would the time complexity change?