Why utility types are needed in Typescript - Performance Analysis
When using utility types in TypeScript, it's important to understand how their operations scale as input types grow.
We want to know how the time to process types changes when the input type has more properties.
Analyze the time complexity of the following utility type usage.
type Readonly = {
readonly [P in keyof T]: T[P];
};
type User = {
id: number;
name: string;
email: string;
};
type ReadonlyUser = Readonly;
This code creates a new type where all properties of User become readonly using a mapped type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over each property key of the input type T.
- How many times: Once for each property in T.
As the number of properties in the input type grows, the utility type processes each property once.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The operations grow linearly with the number of properties.
Time Complexity: O(n)
This means the time to create the new type grows directly with the number of properties in the input type.
[X] Wrong: "Utility types run instantly no matter how big the input type is."
[OK] Correct: Even though utility types are compile-time, they process each property, so more properties mean more work.
Understanding how utility types scale helps you reason about type transformations and their impact on compile time, a useful skill in real projects.
"What if we changed the utility type to recursively apply Readonly to nested objects? How would the time complexity change?"