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.
tsclassOctopus {readonlyname : string;readonlylegs = 8; // Gán trong field initializer là OKconstructor() {this.name = "Octo"; // Gán trong constructor là OK}}
tsclassOctopus {readonlyname : string;readonlylegs = 8; // Gán trong field initializer là OKconstructor() {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ị.
tsconstoctopus = newOctopus ();Cannot assign to 'legs' because it is a read-only property.2540Cannot assign to 'legs' because it is a read-only property.octopus .= 16; legs
tsconstoctopus = newOctopus ();Cannot assign to 'legs' because it is a read-only property.2540Cannot assign to 'legs' because it is a read-only property.octopus .= 16; legs
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.
tsclassOctopus {readonlyname = "Octo";setName (newName : string): void {this.Cannot assign to 'name' because it is a read-only property.2540Cannot assign to 'name' because it is a read-only property.= name newName ;}}
tsclassOctopus {readonlyname = "Octo";setName (newName : string): void {this.Cannot assign to 'name' because it is a read-only property.2540Cannot assign to 'name' because it is a read-only property.= name newName ;}}
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.