Readonly class properties in Typescript - Time & Space Complexity
We want to understand how the time it takes to run code with readonly class properties changes as the input grows.
Specifically, does making properties readonly affect how long the program takes to run?
Analyze the time complexity of the following code snippet.
class Point {
readonly x: number;
readonly y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
distance() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
const points: Point[] = [];
for (let i = 0; i < n; i++) {
points.push(new Point(i, i));
}
for (const p of points) {
console.log(p.distance());
}
This code creates n points with readonly x and y values, then calculates and prints their distances from the origin.
- Primary operation: Looping through the array of points to calculate distance.
- How many times: Exactly n times, once for each point.
As the number of points n grows, the number of distance calculations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 distance calculations |
| 100 | 100 distance calculations |
| 1000 | 1000 distance calculations |
Pattern observation: The work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of points.
[X] Wrong: "Making properties readonly makes the code run faster because values can't change."
[OK] Correct: Readonly only prevents changes in code but does not speed up how many times operations run.
Understanding how readonly properties affect performance helps you explain code design choices clearly and confidently.
"What if we added a nested loop inside the distance method to do extra work? How would the time complexity change?"
Practice
readonly keyword do when used on a class property in TypeScript?Solution
Step 1: Understand the purpose of
Thereadonlyreadonlykeyword marks a property so it cannot be changed after it is set initially.Step 2: Check when assignment is allowed
Assignment to areadonlyproperty is only allowed during declaration or inside the constructor.Final Answer:
It prevents the property from being changed after initialization. -> Option CQuick Check:
Readonly means fixed value after set [OK]
- Thinking readonly makes property private
- Assuming readonly allows changes anytime
- Confusing readonly with deleting properties
id of type number in a TypeScript class?Solution
Step 1: Recall TypeScript readonly syntax
The correct syntax placesreadonlybefore the property name and type.Step 2: Check each option
readonly id: number; matches the correct syntax:readonly id: number;. Others misuse keywords or order.Final Answer:
readonly id: number; -> Option BQuick Check:
Readonly keyword before property name [OK]
- Using const inside class properties
- Placing readonly after the type
- Combining let with readonly incorrectly
class User {
readonly name: string;
constructor(name: string) {
this.name = name;
}
changeName(newName: string) {
// @ts-ignore
this.name = newName;
}
}
const user = new User('Alice');
user.changeName('Bob');
console.log(user.name);Solution
Step 1: Understand readonly assignment rules
Thenameproperty is readonly and assigned in the constructor, so initial value is 'Alice'. TypeScript enforces this at compile-time.Step 2: Analyze the changeName method
The@ts-ignoresuppresses the TypeScript compile error for assigning to readonly. The code compiles to plain JavaScript, where objects are mutable, sothis.name = newName;sets it to 'Bob' at runtime.Final Answer:
Bob -> Option DQuick Check:
Readonly is compile-time only; runtime allows changes [OK]
- Thinking readonly prevents runtime changes
- Expecting compilation error despite @ts-ignore
- Believing output remains 'Alice'
class Product {
readonly price: number;
constructor() {
// No assignment to price here
}
}
const p = new Product();
p.price = 100;Solution
Step 1: Check readonly property initialization
The readonly propertypricemust be assigned during declaration or in the constructor.Step 2: Analyze constructor and assignment
The constructor does not assignprice, so TypeScript reports an error about missing initialization.Final Answer:
Error: readonly property 'price' is not initialized. -> Option AQuick Check:
Readonly props must be initialized at declaration or constructor [OK]
- Trying to assign readonly property after construction
- Ignoring missing initialization error
- Confusing readonly with private
version property while keeping id readonly?class Document {
readonly id: string;
version: number;
constructor(id: string, version: number) {
this.id = id;
this.version = version;
}
}Solution
Step 1: Understand readonly usage
Theidshould remain readonly to keep it fixed after creation.Step 2: Allow version updates
Theversionproperty is not readonly, so it can be updated safely anytime, for example via a method.Final Answer:
Keepidreadonly and updateversionnormally via a method. -> Option AQuick Check:
Readonly for fixed, normal for changeable [OK]
- Making all properties readonly and losing flexibility
- Removing readonly from fixed properties
- Confusing which property should be updated
Ready to prove it?
Pass the test and this pattern moves unknown
