gpt4 book ai didi

typescript - 使用可选链接运算符时,类型上不存在属性 'x'

转载 作者:行者123 更新时间:2023-12-05 02:39:12 28 4
gpt4 key购买 nike

我想在 typescript 中使用可选的链接运算符,但我收到错误 Property 'dog' does not exist on type '{ name: string; cat: Record<string, string>; }'.. typescript 提示的错误完全有道理,但我想知道我是否可以四处走走? playground

const adventurer: {name: string;cat:Record<string, string>} = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};

const dogName = adventurer?.dog;
console.log(dogName);

最佳答案

为什么会这样?

您通过为 adventurer 提供类型来告诉 TS 编译器,adventurer永远 具有属性 dog(编辑:谢谢@感谢 jcalz 指出这不是完全是真的。请查看下面的评论以获取更多信息)。有两种主要的解决方法:

通过断言另一种类型(如任何类型)告诉 TypeScript 你更了解

const dogName = (adventurer as any)?.dog;
console.log(dogName);

更改冒险家的类型以选择性地包括dog

const adventurer: {name: string;cat:Record<string, string>; dog?: string} = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};

const dogName = adventurer?.dog;
console.log(dogName);

关于typescript - 使用可选链接运算符时,类型上不存在属性 'x',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69211120/

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