gpt4 book ai didi

TypeScript:迭代接口(interface)字段不起作用

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

我正在尝试遍历具有接口(interface)的对象的键,但 TypeScript 无法识别键的类型。

interface Resources {
food?: number
water?: number
wood?: number
coal?: number
stone?: number
metal?: number
oil?: number
power?: number
}

class Game {
resources: Resources = {}

addResources = (newResources: Resources) => {
Object.keys(newResources).forEach(key => {
// Error:(17, 11) TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Resources'.
// No index signature with a parameter of type 'string' was found on type 'Resources'.
if (this.resources[key]) {
this.resources[key] += newResources[key]
} else {
this.resources[key] = newResources[key]
}
})
}
}

我应该如何输入它以便 Typescript 能够理解迭代?

最佳答案

是的,Object.keys()返回 string[]这是故意的https://github.com/Microsoft/TypeScript/issues/12870

(Object.keys(newResources) as Array<keyof Resources>).forEach(...)为了救援。

更新

(Object.keys(newResources) as Array<keyof typeof newResources>).forEach(...)也有帮助。

关于TypeScript:迭代接口(interface)字段不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554070/

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