0
0
Typescriptprogramming~5 mins

Basic mapped type syntax in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Basic mapped type syntax
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the number of keys increases, the work to create the mapped type grows proportionally.

Input Size (n)Approx. Operations
33
1010
100100

Pattern observation: The work grows in a straight line with the number of keys.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the mapped type grows directly with the number of keys.

Common Mistake

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

Interview Connect

Understanding how mapped types scale helps you reason about type transformations and their cost in larger codebases.

Self-Check

"What if the mapped type included nested mapped types? How would the time complexity change?"