Nominal typing class
Trong TypeScript, nếu class có ít nhất một property không public, class đó sẽ trở thành nominal typing thay vì structural subtyping.
Ví dụ, chỉ cần đặt property id trùng tên trong class UserId và GroupId thành private là không thể gán lẫn nhau.
tsclassUserId {private readonlyid : string;constructor(id : string) {this.id =id ;}}classGroupId {private readonlyid : string;constructor(id : string) {this.id =id ;}}constType 'GroupId' is not assignable to type 'UserId'. Types have separate declarations of a private property 'id'.2322Type 'GroupId' is not assignable to type 'UserId'. Types have separate declarations of a private property 'id'.: userId UserId = newGroupId ("...");
tsclassUserId {private readonlyid : string;constructor(id : string) {this.id =id ;}}classGroupId {private readonlyid : string;constructor(id : string) {this.id =id ;}}constType 'GroupId' is not assignable to type 'UserId'. Types have separate declarations of a private property 'id'.2322Type 'GroupId' is not assignable to type 'UserId'. Types have separate declarations of a private property 'id'.: userId UserId = newGroupId ("...");
Cách này không chỉ áp dụng cho field mà còn có hiệu quả tương tự với private method hoặc protected property.
Thông tin liên quan
📄️ Structural typing
Đối với ngôn ngữ lập trình, hệ thống kiểu là một chủ đề quan trọng. Hệ thống kiểu là tập hợp các quy tắc gán "kiểu" cho các giá trị và biến khác nhau trong chương trình. Những quy tắc này quyết định tính chất và cách xử lý dữ liệu. Đặc biệt, cách phân biệt giữa các kiểu và ngược lại, cách xác định tính tương thích giữa các kiểu là chủ đề liên quan trực tiếp đến tính dễ sử dụng và an toàn của ngôn ngữ.