[英]Typescript compiler type assignment error ignored
我有以下情況:
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer;
編譯時不會產生錯誤,在我看來這是錯誤的行為。 這似乎是由於Customer
和CustomerLayoutViewModel
完全相同。
問題是隨着時間的推移它們將不完全相同,並且我希望上面的代碼給出編譯錯誤,因為類型不同。
所以我的問題是:在上述示例中,如何配置編譯器以產生錯誤?
這不會產生編譯錯誤,因為您尚未分配customer
或customerViewModel
的類型,但是如果執行類似的操作,則應該得到編譯時錯誤:
const customer:Customer = new Customer();
let customerViewModel:CustomerLayoutViewModel = new CustomerLayoutViewModel();
customerViewModel = customer;
Typescript在確定類型兼容性時使用結構化類型。 這意味着,如果兩種類型具有兼容的結構,則它們將是兼容的:
class Customer { name: string }
class CustomerLayoutViewModel { name: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // OK compatible
如果Customer
具有額外的屬性,這些類型仍然兼容,則沒有機會有人通過customerViewModel
訪問不存在的內容:
class Customer { name: string; fullName: string }
class CustomerLayoutViewModel { name: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; // still OK compatible
如果CustomerLayoutViewModel
具有額外的必需屬性,則會出現兼容性錯誤:
class Customer { name: string }
class CustomerLayoutViewModel { name: string; fullName: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; //error now
確保類型不兼容的一種方法是將私有字段添加到類。 如果名稱相同,則私有字段將與任何其他類事件中的任何其他字段不兼容:
class Customer { private x: string }
class CustomerLayoutViewModel { private x: string }
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer; //error Types have separate declarations of a private property 'x'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.