简体   繁体   English

打字稿中的奇怪类型检查

[英]Strange type checking in typescript

Case 1情况1

let d: { id: number };
d = { id: 2, name: 'archer' }; // compilation error 

Case 2案例二

  let e: { id: number };
  let e1 = { id: 2, name: 'archer' };
  e = e1; // okay

Conclusion结论

It seams that typescript doesn't check the compatibility when assigning one variable to another, but it does when assigning and object literal to a variable.它认为打字稿在将一个变量分配给另一个变量时不会检查兼容性,但在将对象文字分配给变量时会检查。

Also, I'm confused about case 2 because according to the handbook the type checker will only do the type-checking based on the shape.另外,我对案例 2感到困惑,因为根据手册,类型检查器只会根据形状进行类型检查。

From the link you added从您添加的链接

... Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. ...对象文字在将它们分配给其他变量或将它们作为参数传递时会得到特殊处理并进行额外的属性检查 If an object literal has any properties that the “target type” doesn't have, you'll get an error如果对象字面量具有“目标类型”没有的任何属性,您将收到错误消息

That's why case 1 fails.这就是案例 1 失败的原因。

Type Compatibility - https://www.typescriptlang.org/docs/handbook/type-compatibility.html类型兼容性 - https://www.typescriptlang.org/docs/handbook/type-compatibility.html

For Case 2 the following rule applied:对于案例 2 ,应用了以下规则:

To check whether y can be assigned to x, the compiler checks each property of x to find a corresponding compatible property in y.为了检查 y 是否可以分配给 x,编译器检查 x 的每个属性以在 y 中找到相应的兼容属性。 In this case, y must have a member called name that is a string.在这种情况下, y 必须有一个名为 name 的成员,它是一个字符串。 It does, so the assignment is allowed.确实如此,因此允许分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM