Sub topic 9
Readonly Properties in TypeScript
This chapter assumes you know basic TypeScript types, constructors, and the this keyword. You will learn how readonly protects a class property after initialization.
What `readonly` means
A readonly property can be assigned when it is declared or inside the class constructor. After construction, TypeScript prevents assignments to that property.
class Account {
readonly id: string;
private balance: number;
constructor(id: string, initialBalance: number) {
this.id = id;
this.balance = initialBalance;
}
deposit(amount: number): void {
if (amount <= 0) {
throw new Error("Amount must be positive");
}
this.balance += amount;
}
}
const account = new Account("a-1", 100);
account.deposit(50);
console.log(account.id); // a-1
console.log(account.balance); // Error: balance is private
// account.id = "a-2"; // Error: Cannot assign to 'id'The id should stay constant, so the class exposes it as readonly. The balance can change, so it is not readonly. Its private modifier prevents outside code from changing it directly.
A property initializer is another valid initialization location:
class Session {
readonly createdAt = new Date();
readonly token: string;
constructor(token: string) {
this.token = token;
}
}Parameter properties
A readonly parameter property declares a field and initializes it from the constructor parameter:
class Point {
constructor(
public readonly x: number,
public readonly y: number
) {}
distanceFromOrigin(): number {
return Math.sqrt(this.x ** 2 + this.y ** 2);
}
}
const point = new Point(3, 4);
console.log(point.distanceFromOrigin()); // 5
// point.x = 10; // ErrorThis is shorthand for declaring x and y as fields, then assigning them in the constructor.
Readonly is shallow
readonly protects the property reference, not every value inside the referenced object or array.
class Playlist {
readonly songs: string[];
constructor(songs: string[]) {
this.songs = songs;
}
addSong(song: string): void {
this.songs.push(song); // Allowed
}
}
const playlist = new Playlist(["Intro"]);
playlist.songs.push("Finale"); // Allowed
// playlist.songs = []; // ErrorUse ReadonlyArray<string> when callers must not add, remove, or replace array elements through that property:
class SafePlaylist {
constructor(public readonly songs: ReadonlyArray<string>) {}
}
const safePlaylist = new SafePlaylist(["Intro"]);
// safePlaylist.songs.push("Finale"); // ErrorThis still does not deeply freeze nested objects at runtime.
Initialization and design
With strictPropertyInitialization enabled, every non-optional field must receive a value in its declaration or constructor. A readonly field is no exception. Prefer normal initialization over the definite-assignment assertion (!) because the compiler can then verify the property is actually set.
Exercise
Why can a method change a private balance but not a readonly account ID?
Show answer
readonly prevents later assignment to the ID, while the balance is mutable. private controls who can access the balance; it does not make the balance constant.