Why advanced generics matter in Typescript - Performance Analysis
We want to see how using advanced generics affects the speed of TypeScript code during compilation and type checking.
How does adding complex generic types change the work the compiler does?
Analyze the time complexity of the following TypeScript generic type.
type Flatten<T> = T extends Array<infer U> ? Flatten<U> : T;
type DeepArray = number[][][][];
type Result = Flatten<DeepArray>;
This code defines a type that flattens nested arrays to their base element type.
Look for repeated checks or expansions done by the compiler.
- Primary operation: Recursive conditional type checks if the type is an array and unwraps it.
- How many times: Once for each nested array level until the base type is reached.
Each nested array adds one more recursive step the compiler must check.
| Input Size (nesting depth) | Approx. Operations |
|---|---|
| 2 | 2 recursive checks |
| 4 | 4 recursive checks |
| 10 | 10 recursive checks |
Pattern observation: The work grows linearly with the depth of nested arrays.
Time Complexity: O(n)
This means the compiler work grows in a straight line with how deep the generics nest.
[X] Wrong: "Advanced generics always slow down code a lot regardless of input size."
[OK] Correct: The slowdown depends on how complex and deep the generics are, not just that they exist.
Understanding how generics affect compile time helps you write clear, efficient types and shows you think about code quality beyond just correctness.
What if we changed the recursive generic to handle objects with nested arrays? How would that affect the time complexity?