Basic mapped type syntax in Typescript - Time & Space Complexity
We want to understand how the time it takes to create a new type changes as the number of keys grows.
How does the process of mapping over keys affect the work done?
Analyze the time complexity of the following code snippet.
type Options = 'width' | 'height' | 'color';
type MappedType<T extends string> = {
[K in T]: number;
};
type StyleOptions = MappedType<Options>;
This code creates a new type by mapping over a set of string keys and assigning each a number type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Mapping over each key in the union type
T. - How many times: Once for each key in the union (here 3 times for 'width', 'height', 'color').
As the number of keys increases, the work to create the mapped type grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The work grows in a straight line with the number of keys.
Time Complexity: O(n)
This means the time to create the mapped type grows directly with the number of keys.
[X] Wrong: "Mapping over keys happens instantly no matter how many keys there are."
[OK] Correct: Each key requires a step to create its property, so more keys mean more work.
Understanding how mapped types scale helps you reason about type transformations and their cost in larger codebases.
"What if the mapped type included nested mapped types? How would the time complexity change?"