我有以下情况:
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
确保类型不兼容的一种方法是将私有(private)字段添加到类中。如果名称相同,私有(private)字段将与任何其他类事件中的任何其他字段不兼容:
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'.
关于javascript - typescript 编译器类型赋值错误被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52965234/