Readonly properties in Typescript - Time & Space 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.
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 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.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of steps stays the same no matter how many users or properties exist.
Time Complexity: O(1)
This means the time to update a property does not grow with input size; it stays constant.
[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.
Understanding that readonly properties do not affect runtime speed shows you know the difference between compile-time and runtime, a useful skill in coding.
"What if we added a loop to update many user names at once? How would the time complexity change?"