我有以下情况:
const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();
customerViewModel = customer;
这在编译时不会产生错误,在我看来这是错误的行为。这似乎是由于Customer
和CustomerLayoutViewModel
完全相同的事实。
问题是随着时间的推移,它们将不相同,我希望上面的代码给出编译错误,因为类型不同。
所以我的问题:如何配置编译器以在上面的例子中产生错误?
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'.
这不会给出编译错误,因为您没有分配customer
或customerViewModel
的类型,但是如果您执行以下操作,那么您应该得到编译时错误:
const customer:Customer = new Customer();
let customerViewModel:CustomerLayoutViewModel = new CustomerLayoutViewModel();
customerViewModel = customer;