Readonly Properties in TypeScript Classes
What you'll learn: How to use the readonly modifier to prevent property reassignment after a class instance is constructed.
What Are Readonly Properties?
The readonly modifier marks a class property as unchangeable after initialization. Once you set a readonly property—either through direct initialization or in the constructor—TypeScript will prevent you from reassigning it anywhere else in your code.
Think of it like installing a one-way valve: water can flow in during setup, but once it's in place, nothing can push it back out or replace it.
How Readonly Works
You add readonly before the property name in your class definition:
class BankAccount {
readonly accountNumber: string;
balance: number;
constructor(accountNumber: string, initialBalance: number) {
this.accountNumber = accountNumber; // ✓ Allowed in constructor
this.balance = initialBalance;
}
updateBalance(amount: number): void {
this.balance += amount; // ✓ balance is not readonly
// this.accountNumber = "123"; // ✗ Error: Cannot assign to 'accountNumber' because it is a read-only property
}
}
const account = new BankAccount("ACC-001", 1000);
console.log(account.accountNumber); // ✓ Reading is fine
// account.accountNumber = "ACC-002"; // ✗ Error: Cannot assign
Initialization Requirements
Readonly properties must be initialized either:
- At declaration:
readonly id: string = "default"; - In the constructor: As shown in the example above
You cannot leave them uninitialized and set them later—that would violate the readonly contract.
When to Use Readonly
Use readonly for properties that represent:
- Identity values (IDs, keys, account numbers)
- Configuration set at creation time
- Immutable metadata (creation timestamps, entity types)
This makes your intent clear: "This value is permanent once the object exists."
Key Takeaway: The readonly modifier prevents property reassignment after construction, enforcing immutability at compile time and making your classes safer and more predictable.