Mapped type with template literals in Typescript - Time & Space Complexity
We want to understand how the time it takes to create a new type grows when using mapped types with template literals in TypeScript.
Specifically, how does the process scale as the number of keys increases?
Analyze the time complexity of the following code snippet.
type Options = "width" | "height" | "color";
type PrefixedOptions = {
[K in Options as `get${Capitalize}`]: () => string;
};
This code creates a new type by taking each key from Options, capitalizing it, and prefixing it with "get" to form new keys.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over each key in the union
Options. - How many times: Once for each key in
Options(3 times in this example).
As the number of keys in the original type grows, the mapped type processes each key once to create a new key.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the number of keys, increasing in a straight line.
Time Complexity: O(n)
This means the time to create the mapped type grows linearly with the number of keys in the original type.
[X] Wrong: "The mapped type runs in constant time no matter how many keys there are."
[OK] Correct: Each key must be processed individually to create the new keys, so more keys mean more work.
Understanding how mapped types scale helps you reason about type transformations and their impact on compile-time performance, a useful skill in real projects.
"What if we added nested mapped types inside the template literal? How would the time complexity change?"