gpt4 book ai didi

typescript - 有趣的行为 : Object literal may only specify known properties

转载 作者:行者123 更新时间:2023-12-04 12:59:02 55 4
gpt4 key购买 nike

这里有类似的问题,我可以理解这个错误的性质:

type Person = { name: string };

// Error: Object literal may only specify known properties, and 'age' does not exist in type 'Person'.
const person: Person = { name: 'Sarah', age: 13 };

所以这失败了,因为属性 age不是类型 Person 的一部分这是有道理的。

但是,我可以毫无问题地做到这一点:
type Person = { name: string };

const obj = { name: 'Sarah', age: 13 };
const person: Person = obj;

console.log(person); // { name: 'Sarah', age: 13 }

为什么第一个失败而第二个没有 - 这两个例子不应该都失败还是都通过?

至于我,这两个代码片段是相同的。他们不是吗?

更新:

这是 Typescript Handbook 中对此行为的解释:

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.

最佳答案

从 TypeScript 1.6 开始,对象字面量中的属性在它们被分配的类型中没有对应的属性会被标记为错误。

基本上:TS 编译器知道永远不会使用年龄,这就是为什么它生你的气。在第二个例子中,它不知道 age 永远不会被用作它的正常对象的一部分。一旦它被复制到 Person 只有名字继续存在

TLDR:当用文字初始化时,TSC 是严格的

关于typescript - 有趣的行为 : Object literal may only specify known properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61698807/

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