Nhảy tới nội dung

Readonly modifier trong class

Trong TypeScript, thêm readonly modifier cho field để biến field đó thành chỉ đọc.

Field chỉ đọc chỉ có thể gán giá trị trong constructor hoặc field initializer.

ts
class Octopus {
readonly name: string;
readonly legs = 8; // Gán trong field initializer là OK
 
constructor() {
this.name = "Octo"; // Gán trong constructor là OK
}
}
ts
class Octopus {
readonly name: string;
readonly legs = 8; // Gán trong field initializer là OK
 
constructor() {
this.name = "Octo"; // Gán trong constructor là OK
}
}

Field chỉ đọc sẽ báo lỗi compile khi cố gắng gán lại giá trị.

ts
const octopus = new Octopus();
octopus.legs = 16;
Cannot assign to 'legs' because it is a read-only property.2540Cannot assign to 'legs' because it is a read-only property.
ts
const octopus = new Octopus();
octopus.legs = 16;
Cannot assign to 'legs' because it is a read-only property.2540Cannot assign to 'legs' because it is a read-only property.

Ngay cả trong xử lý của method, việc gán lại giá trị cho field chỉ đọc cũng không được phép.

ts
class Octopus {
readonly name = "Octo";
 
setName(newName: string): void {
this.name = newName;
Cannot assign to 'name' because it is a read-only property.2540Cannot assign to 'name' because it is a read-only property.
}
}
ts
class Octopus {
readonly name = "Octo";
 
setName(newName: string): void {
this.name = newName;
Cannot assign to 'name' because it is a read-only property.2540Cannot assign to 'name' because it is a read-only property.
}
}

Thông tin liên quan

📄️ Readonly property của object type

Trong TypeScript, có thể đặt property của object thành read-only. Thêm modifier readonly vào property muốn đặt thành read-only. Khi cố gán giá trị cho property read-only, TypeScript compiler sẽ cảnh báo không thể gán.

📄️ Readonly modifier của interface

Trong interface của TypeScript, có thể định nghĩa field chỉ đọc bằng cách thêm readonly modifier cho field.