简体   繁体   中英

Strange type checking in typescript

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

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.

Type Compatibility - https://www.typescriptlang.org/docs/handbook/type-compatibility.html

For Case 2 the following rule applied:

To check whether y can be assigned to x, the compiler checks each property of x to find a corresponding compatible property in y. In this case, y must have a member called name that is a string. It does, so the assignment is allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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