0
0
Typescriptprogramming~5 mins

Readonly properties in interfaces in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Readonly properties in interfaces
O(1)
Understanding Time Complexity

Let's see how readonly properties in interfaces affect the time it takes to run code.

We want to know if making properties readonly changes how long operations take as data grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


interface User {
  readonly id: number;
  name: string;
}

function updateUserName(user: User, newName: string) {
  // user.id = 5; // Error: Cannot assign to 'id' because it is a read-only property
  user.name = newName;
}

const user: User = { id: 1, name: 'Alice' };
updateUserName(user, 'Bob');

This code defines a user with a readonly id and a writable name, then updates the name.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single property assignment to user.name.
  • How many times: Happens once per function call, no loops or recursion.
How Execution Grows With Input

Changing the name property takes the same time no matter how many users or properties exist.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The operation count stays the same regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to update a property is constant and does not grow with input size.

Common Mistake

[X] Wrong: "Making a property readonly will slow down property access or assignment."

[OK] Correct: Readonly is a compile-time check in TypeScript and does not affect runtime speed or how many steps the program takes.

Interview Connect

Understanding that readonly properties are about safety, not speed, helps you explain design choices clearly in interviews.

Self-Check

"What if we looped over an array of users and updated each name? How would the time complexity change?"