gpt4 book ai didi

typescript - 为什么我可以通过将对象的引用传递给函数而不是其文字形式的对象来避免在 typescript 中进行过多的属性检查?

转载 作者:行者123 更新时间:2023-12-03 18:45:28 25 4
gpt4 key购买 nike

看看这个示例 typescript 代码

function printLabel(labelledObj: { label: string }) {
console.log(labelledObj.label);
}

printLabel({ size: 10, label: 'hello' });

上面的代码编译失败,错误如下:

1.ts:6:14 - error TS2345: Argument of type '{ size: number; label: string; }' is not assignable to parameter of type '{ label: string; }'. Object literal may only specify known properties, and 'size' does not exist in type '{ label: string; }'.



简而言之, size 是一个多余的属性,不符合 { label: string } 类型导致编译器大喊大叫。让我们稍微修改一下上面的代码片段:
function printLabel(labelledObj: { label: string }) {
console.log(labelledObj.label);
}
const obj = { size: 10, label: 'hello' }
printLabel(obj);

现在我们将在前面的例子中传递给 printLabel 的对象文字提取到一个名为 obj 的中间引用中,奇怪的是现在它没有提示并且完美地工作。为什么 typescript 的行为如此?

最佳答案

这是设计使然。简而言之,Typescript 创建者这样做是因为他们知道 Javascript 是一种非常动态的语言,有很多这样的用例。

你应该仔细阅读:https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks
(不过我敢打赌这个问题是从阅读中产生的)。

Object literals get special treatment



他们的逻辑可能是这样的:如果你有一个变量,那么它可能来自某个第三方,你无能为力。另一方面,如果您传递对象字面量,那么您要对其正确的类型负责。

关于typescript - 为什么我可以通过将对象的引用传递给函数而不是其文字形式的对象来避免在 typescript 中进行过多的属性检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52852278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com