0
0
Typescriptprogramming~5 mins

Mapped type modifiers (readonly, optional) in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Mapped type modifiers (readonly, optional)
O(n)
Understanding Time Complexity

When using mapped type modifiers like readonly and optional in TypeScript, it's helpful to understand how the time to create these types grows as the number of properties increases.

We want to see how the process of applying these modifiers scales with input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    type ReadonlyProps<T> = {
      readonly [P in keyof T]: T[P];
    };

    type OptionalProps<T> = {
      [P in keyof T]?: T[P];
    };
    

This code creates new types by adding readonly or optional modifiers to each property of a given type T.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Iterating over each property key in the type T.
  • How many times: Once for every property in T.
How Execution Grows With Input

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

Input Size (n)Approx. Operations
1010 property modifications
100100 property modifications
10001000 property modifications

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 apply readonly or optional modifiers grows directly with the number of properties.

Common Mistake

[X] Wrong: "Adding modifiers to a type is instant and does not depend on the number of properties."

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

Interview Connect

Understanding how mapped types scale helps you reason about type transformations in real projects, showing you can think about code efficiency beyond just runtime.

Self-Check

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