0
0
Typescriptprogramming~5 mins

Readonly utility type in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Readonly utility type
O(n)
Understanding Time Complexity

We want to understand how the time it takes to use the Readonly utility type changes as the size of the object grows.

Specifically, how does making an object readonly affect the number of operations when the object has many properties?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

    interface User {
      name: string;
      age: number;
      email: string;
    }

    const user: Readonly<User> = {
      name: "Alice",
      age: 30,
      email: "alice@example.com"
    };
    

This code creates a readonly version of a User object by applying the Readonly utility type to all its properties.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The mapped type loops over each property key in the object type.
  • How many times: Once for each property in the object (for example, 3 times for User).
How Execution Grows With Input

As the number of properties in the object grows, the number of operations grows in the same way.

Input Size (n)Approx. Operations
33 (one per property)
1010
100100

Pattern observation: The operations increase directly with the number of properties, growing in a straight line.

Final Time Complexity

Time Complexity: O(n)

This means the time to create a readonly type grows linearly with the number of properties in the object.

Common Mistake

[X] Wrong: "Making an object readonly happens instantly no matter how big it is."

[OK] Correct: The type system processes each property one by one, so more properties mean more work.

Interview Connect

Understanding how utility types like Readonly work helps you reason about type transformations and their costs, a useful skill in real projects and interviews.

Self-Check

"What if we changed Readonly to make only some properties readonly? How would the time complexity change?"