打字稿编译器类型分配错误被忽略

Typescript compiler type assignment error ignored

我有以下场景:

const customer = new Customer();
let customerViewModel = new CustomerLayoutViewModel();

customerViewModel = customer;

这在编译时不会产生错误,在我看来这是错误的行为。这似乎是因为 CustomerCustomerLayoutViewModel 完全相同。

问题是随着时间的推移它们将不相同,我希望上面的代码给出编译错误,因为类型不同。

所以我的问题是:如何配置编译器以在上面的示例中产生错误?

这不会给出编译错误,因为你没有分配 customercustomerViewModel 的类型,但是如果你这样做那么你应该得到编译时错误:

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。如果名称相同,私有字段将与任何其他 class 事件中的任何其他字段不兼容:

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'.