Sub topic 9
Readonly fields in classes
This chapter assumes basic TypeScript classes, constructors, and type annotations. It focuses on readonly fields: properties that TypeScript allows you to assign only during initialization or construction.
A readonly field is useful for values that identify an object or describe a fact that should not change after creation. Common examples include an account ID, a user ID, or a creation timestamp.
Declaring a readonly field
Place readonly before the field name. The field must also have a type, an initializer, or both.
class Account {
readonly id: string;
balance: number;
constructor(id: string, openingBalance: number) {
this.id = id;
this.balance = openingBalance;
}
deposit(amount: number): void {
this.balance += amount;
}
}
const account = new Account("acct-100", 500);
console.log(account.id); // acct-100
account.deposit(100); // balance may change
// account.id = "acct-200"; // Error: Cannot assign to 'id'
// account.id = "acct-200'; // Error: Cannot assign to 'id'The constructor may assign this.id because construction is the allowed initialization period. A later method or caller may read id, but may not assign a new value to it.
The balance field is mutable because it does not have the readonly modifier. Making one field readonly does not make every field in the object readonly.
Initializers and strict property initialization
You can give a readonly field its value at its declaration. Every instance then starts with the same value unless the value is computed.
class Job {
readonly kind = "background";
readonly createdAt = new Date();
constructor(readonly id: string) {}
}
const job = new Job("job-1");
console.log(job.kind); // background
console.log(job.id); // job-1The constructor parameter readonly id: string is a parameter property. TypeScript creates a field named id, assigns the parameter to it, and marks the field readonly.
If strictPropertyInitialization is enabled, TypeScript checks that each non-optional field receives a value in the declaration or every constructor path.
class User {
readonly id: string;
constructor(id: string, valid: boolean) {
if (!valid) {
throw new Error("Invalid user");
}
this.id = id;
}
}The assignment occurs on every path that completes normally. If a constructor can finish without assigning id, TypeScript reports an error.
A definite assignment assertion, written as !, tells TypeScript that another process will initialize the field. Use it only when that guarantee is real.
class Service {
readonly name!: string;
initialize(name: string): void {
this.name = name;
}
}This compiles, but the type checker cannot protect you if initialize is never called. Prefer constructor or declaration initialization when possible.
What assignments are allowed?
TypeScript permits assignment in a field initializer and in the class constructor. It rejects assignment in ordinary methods.
class Document {
readonly id: string;
constructor(id: string) {
this.id = id; // allowed
}
rename(newId: string): void {
// this.id = newId; // Error
}
}A subclass cannot normally reassign a readonly field inherited from its parent. The parent class owns the initialization contract.
Readonly is shallow
Readonly protects the field reference, not necessarily the value inside that reference.
class Project {
readonly labels: string[];
constructor(labels: string[]) {
this.labels = labels;
}
addLabel(label: string): void {
this.labels.push(label); // allowed
}
}
const project = new Project(["typescript"]);
project.addLabel("classes");
// project.labels = []; // Error: the field itself is readonlyThe array can still change because readonly labels prevents replacing the array, but does not prevent calls such as push. If the contents must not change through the class, use a readonly array type.
class SafeProject {
readonly labels: readonly string[];
constructor(labels: readonly string[]) {
this.labels = labels;
}
}This prevents the class from calling mutating array methods. It does not freeze an array at runtime. JavaScript code can still mutate the original array if it keeps a mutable reference.
| Declaration | Replacing the field | Mutating the array |
|---|---|---|
| `labels: string[]` | Allowed | Allowed |
| `readonly labels: string[]` | Rejected | Allowed |
| `readonly labels: readonly string[]` | Rejected | Rejected through this field |
Exercise
In the Account class, why is assigning this.id in the constructor allowed but assigning it in deposit rejected? What does readonly balance fail to protect if its type is number[]?
Show answer
TypeScript allows a readonly field to be initialized in its declaration or constructor, but rejects later assignments. readonly balance: number[] prevents replacing the array reference, but it does not prevent changing the array's contents.