Mapped type modifiers (readonly, optional) in Typescript - Time & Space Complexity
When using mapped type modifiers like readonly and optional in TypeScript, it's helpful to understand how the time to create these types grows as the number of properties increases.
We want to see how the process of applying these modifiers scales with input size.
Analyze the time complexity of the following code snippet.
type ReadonlyProps<T> = {
readonly [P in keyof T]: T[P];
};
type OptionalProps<T> = {
[P in keyof T]?: T[P];
};
This code creates new types by adding readonly or optional modifiers to each property of a given type T.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over each property key in the type
T. - How many times: Once for every property in
T.
As the number of properties in the input type grows, the time to create the mapped type grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 property modifications |
| 100 | 100 property modifications |
| 1000 | 1000 property modifications |
Pattern observation: The work grows in a straight line with the number of properties.
Time Complexity: O(n)
This means the time to apply readonly or optional modifiers grows directly with the number of properties.
[X] Wrong: "Adding modifiers to a type is instant and does not depend on the number of properties."
[OK] Correct: Each property must be processed individually, so more properties mean more work.
Understanding how mapped types scale helps you reason about type transformations in real projects, showing you can think about code efficiency beyond just runtime.
"What if we nested mapped types inside each other? How would the time complexity change?"