Conditional type syntax in Typescript - Time & Space Complexity
We want to understand how the time it takes to evaluate a conditional type changes as the input type changes.
How does the complexity grow when TypeScript checks conditions on types?
Analyze the time complexity of the following TypeScript conditional type.
type IsString<T> = T extends string ? true : false;
// Usage example:
type Test1 = IsString<string>; // true
type Test2 = IsString<number>; // false
This code checks if a type T is a string type and returns true or false accordingly.
Look for repeated checks or evaluations in the conditional type.
- Primary operation: TypeScript checks if T extends string.
- How many times: Once per type evaluation; no loops or recursion here.
The check is simple and happens once per type. Even if T is complex, this conditional runs a single check.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 (simple type) | 1 check |
| 10 (union of 10 types) | 10 checks (one per union member) |
| 100 (union of 100 types) | 100 checks |
Pattern observation: The number of checks grows linearly with the number of union members in the input type.
Time Complexity: O(n)
This means the time to evaluate grows in a straight line as the number of types to check increases.
[X] Wrong: "Conditional types always run instantly regardless of input size."
[OK] Correct: When the input is a union type, TypeScript evaluates the condition for each member, so time grows with the number of members.
Understanding how conditional types scale helps you write efficient type logic and shows you think about performance even in type-level code.
"What if we changed the conditional type to check nested conditional types? How would the time complexity change?"