0
0
Typescriptprogramming~5 mins

Readonly properties in Typescript - Time & Space Complexity

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

Let's see how using readonly properties affects how long a program takes to run.

We want to know if readonly changes how many steps the program needs as input 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 readonly property
  user.name = newName;
}
    

This code defines a user with a readonly id and a name that can change. It updates the name but not the id.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps here.
  • How many times: The update runs once per call, no matter the input size.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The number of steps stays the same no matter how many users or properties exist.

Final Time Complexity

Time Complexity: O(1)

This means the time to update a property does not grow with input size; it stays constant.

Common Mistake

[X] Wrong: "Readonly properties make the program slower because they add checks at runtime."

[OK] Correct: Readonly is a compile-time check in TypeScript and does not add extra steps when the program runs.

Interview Connect

Understanding that readonly properties do not affect runtime speed shows you know the difference between compile-time and runtime, a useful skill in coding.

Self-Check

"What if we added a loop to update many user names at once? How would the time complexity change?"