0
0
Typescriptprogramming~5 mins

Why mapped types are needed in Typescript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why mapped types are needed
O(n)
Understanding Time Complexity

We want to see how the time it takes to create new types grows when using mapped types in TypeScript.

How does the process scale as the number of properties increases?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    type Options = {
      width: number;
      height: number;
      color: string;
    };

    type ReadonlyOptions = {
      readonly [K in keyof Options]: Options[K];
    };
    

This code creates a new type by making all properties of an existing type readonly using a mapped type.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Iterating over each property key in the original type.
  • How many times: Once for each property in the type (e.g., width, height, color).
How Execution Grows With Input

As the number of properties grows, the time to create the mapped type grows proportionally.

Input Size (number of properties)Approx. Operations
33 operations (one per property)
1010 operations
100100 operations

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Mapped types create all properties instantly, so time does not grow with more properties."

[OK] Correct: Each property must be processed one by one, so more properties mean more work.

Interview Connect

Understanding how mapped types scale helps you explain how TypeScript handles type transformations efficiently.

Self-Check

"What if we nested mapped types inside each other? How would the time complexity change?"