Welcome back! I am Mihir, and in this lesson we will learn readonly class properties in TypeScript.
readonly means a property can be assigned during initialization, but cannot be reassigned later.
Basic readonly Property
class User {
readonly id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}Valid:
const user = new User(1, "Mihir");
user.name = "Mihir Soni";Invalid:
user.id = 2;readonly with Default Value
class AppConfig {
readonly appName: string = "CodeWithMihir";
}Once the instance is created, appName cannot be reassigned.
readonly Constructor Parameter Property
You can use readonly directly in constructor parameters.
class Product {
constructor(
public readonly id: number,
public name: string
) {}
}This creates an id property and makes it readonly.
readonly Still Allows Reading
const product = new Product(101, "Keyboard");
console.log(product.id);Readonly properties can always be read.
They just cannot be reassigned.
readonly Is Not Deep Immutability
class Cart {
readonly items: string[] = [];
}
const cart = new Cart();
cart.items.push("Keyboard");This is allowed because the items property still points to the same array.
Invalid:
cart.items = [];readonly prevents reassigning the property, not mutating the object inside it.
When to Use readonly
Use readonly for values that should not change after creation.
Good examples:
- database IDs
- creation dates
- configuration names
- fixed labels
- injected dependencies
Quick Recap
readonlyprevents property reassignment.- Readonly properties can be assigned during initialization or in the constructor.
- Constructor parameter properties can be readonly.
readonlyis not deep immutability.- Use it for values that should stay stable after object creation.
Next up, we will learn Getters and Setters →.