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

时间:2018-10-24 09:15:56

标签: javascript typescript error-handling tsconfig

我有以下情况:

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

customerViewModel = customer;

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

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

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

2 个答案:

答案 0 :(得分:0)

这不会产生编译错误,因为您尚未分配customercustomerViewModel的类型,但是如果执行类似的操作,则会出现编译时错误:

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

customerViewModel  = customer;

答案 1 :(得分:0)

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