0
0
Typescriptprogramming~5 mins

Mapped type with template literals in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Mapped type with template literals
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

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
1010
100100
10001000

Pattern observation: The number of operations grows directly with the number of keys, increasing in a straight line.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the mapped type grows linearly with the number of keys in the original type.

Common Mistake

[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.

Interview Connect

Understanding how mapped types scale helps you reason about type transformations and their impact on compile-time performance, a useful skill in real projects.

Self-Check

"What if we added nested mapped types inside the template literal? How would the time complexity change?"