gpt4 book ai didi

javascript - 在以下情况下是否必须声明索引签名?

转载 作者:行者123 更新时间:2023-11-30 11:19:34 24 4
gpt4 key购买 nike

使用 TypeScript 编写代码。

interface Object {
number: number;
string: string;
}

const object: Object = { number: 1, string: 'a' },
object2 = {} as Object;

for (const key of Object.keys(object))
object2[key] = object[key];
=> Element implicitly has an 'any' type because type 'Object' has no index signature.

URL for test

问题

我一直在使用 noImplicitAny 选项来处理 TypeScript。

基本上,我猜它推断出 key 变量是 objectobject2 的键,所以我想我不必声明一个索引签名。

但是我想错了,所以我总是出错。

有没有办法在不声明索引签名的情况下修复错误?

感谢阅读! :)

最佳答案

这里的问题是您希望 Object.keys 返回 (keyof Obj)[] 而不是 string[]。这已经进行了一定程度的讨论,可能是最好的来源here .简而言之,Typescript 的创建者 Anders 评论说:

Once you move to the instantiated type world it degenerates because an object can (and often does) have more properties at run-time than are statically known at compile time.

因此,如果 Object.keys 告诉您它只会给您 numberstring,那么在运行时它实际上可能会有所不同。

因此,如果您想继续使用 Object.keys,那么您将需要提供更明确的类型来告诉 TypeScript 一切正常。

关于javascript - 在以下情况下是否必须声明索引签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297592/

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