javascript - typescript 编译器类型赋值错误被忽略

标签 javascript typescript error-handling tsconfig

我有以下情况:

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

customerViewModel = customer;

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

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

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

最佳答案

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/

相关文章:

javascript - 尝试在 angular2 中使用 stomp.js

python - 从 SQLAlchemy+Postgres 中的 IntegrityError 中获取约束名称

C# Try-catch 不捕获异常

javascript - 如何使用 javascript 计算具有特定类的父节点的所有子节点?

javascript - 动态删除文本框

javascript - 将函数直接分配给构造函数与原型(prototype)分配有什么区别,为什么?

Angular7 和 NgbModal : how to remove default auto focus

typescript - 在 typescript 中使用 never 关键字

asp.net-mvc - [授权]失败后显示404错误页面

javascript - 使用 JavaScript 或 jQuery 提取特定类