Inferring types with infer keyword in Typescript - Time & Space Complexity
We want to understand how the time it takes to infer types using the infer keyword changes as the input type grows.
Specifically, how does the process scale when working with different type structures?
Analyze the time complexity of the following TypeScript type inference using infer.
type ElementType<T> = T extends (infer U)[] ? U : T;
// Example usage:
type A = ElementType<string[]>; // string
type B = ElementType<number>; // number
This code extracts the element type from an array type or returns the type itself if it is not an array.
Look for repeated checks or pattern matches in the type inference.
- Primary operation: Conditional type check with
inferto extract inner type. - How many times: Once per type checked; no loops or recursion here.
The inference happens once per type checked, so the time does not grow with the size of the array type.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The operation count stays the same regardless of input size.
Time Complexity: O(1)
This means the inference takes the same amount of time no matter how big the input type is.
[X] Wrong: "The infer keyword loops over all elements of the array type to find the inner type."
[OK] Correct: The infer keyword works by pattern matching the type structure once, not by iterating over elements.
Understanding how TypeScript infers types quickly helps you write better type-safe code and explain your reasoning clearly in interviews.
What if we changed the type to infer nested arrays like number[][]? How would the time complexity change?