Combining readonly with Access Modifiers
You'll learn: How to use readonly together with public, private, or protected to create immutable properties that respect encapsulation rules.
The Layered Protection Pattern
You've already learned that readonly prevents reassignment at compile time, and that access modifiers (public, private, protected) control who can see a property. When you combine them, you get dual protection: one modifier controls visibility, the other controls mutability.
Think of it like a museum display case:
- The access modifier is the locked door (who can enter the room)
- The readonly is the glass case (even if you're in the room, you can't touch the artifact)
Syntax and Order
The readonly keyword comes after the access modifier:
class BankAccount {
private readonly accountId: string;
protected readonly createdAt: Date;
public readonly owner: string;
constructor(id: string, owner: string) {
this.accountId = id;
this.owner = owner;
this.createdAt = new Date();
}
}
You can initialize readonly properties in the constructor, but never reassign them afterward.
Why Combine Them?
Private + readonly = Internal immutable data that even the class itself shouldn't modify after initialization:
class User {
private readonly userId: string;
constructor(id: string) {
this.userId = id;
}
// This would error - can't modify readonly even inside the class
// regenerateId() {
// this.userId = "new-id"; // Error!
// }
}
Protected + readonly = Data accessible to subclasses but frozen for everyone:
class Vehicle {
protected readonly vin: string;
constructor(vin: string) {
this.vin = vin;
}
}
class Car extends Vehicle {
getVIN() {
return this.vin; // ✓ Can read in subclass
// this.vin = "new"; // ✗ Can't modify
}
}
Public + readonly = Externally visible but immutable:
class Config {
public readonly apiUrl: string = "https://api.example.com";
}
const config = new Config();
console.log(config.apiUrl); // ✓ Can read
// config.apiUrl = "other"; // ✗ Can't modify
Parameter Properties Shorthand
You can combine both modifiers in constructor parameters:
class Transaction {
constructor(
private readonly transactionId: string,
public readonly amount: number,
protected readonly timestamp: Date
) {}
}
This creates three properties with combined visibility and mutability rules in one line.
Key Takeaway:
Combining readonly with access modifiers gives you fine-grained control over both who can access a property and whether they can modify it, enabling immutable encapsulated data.