为什么没有类型错误显示,如果值来作为变量?



我想知道为什么编译器这是一个类型错误,如果一个值被直接写入if类型变量(result_2)),但如果值被写为变量(result_1)则不会。(. 不管怎样,打字稿的使用是正确的吗?

ts操场

type HasID = {  id: number }
const data = {id: 5, age: 3}
const result_1: HasID = data

// Type '{ id: number; age: number; }' is not assignable to type 'HasID'.
// Object literal may only specify known properties, and 'age' does not exist in type 'HasID'.
const result_2: HasID = {id: 5, age: 3} // Error

我找到了一篇关于这个有趣话题的博客文章。总而言之,当你将对象直接赋值给类型化变量(result_2)时,typescript编译器会触发过多的属性检查。

在result_1中,它只检查数据是否包含类型HasId所需的所有强制属性。

看看这篇我找到的关于这个话题的更多信息的博客文章:https://levelup.gitconnected.com/typescript-excess-property-checks-6ffe5584f450

以及typescript文档中的这篇文章(Type compatibility):https://www.typescriptlang.org/docs/handbook/type-compatibility.html

最新更新