I am currently facing an issue while trying to loop through the keys of an object that contains an interface. TypeScript seems to be unable to recognize the type of the key.
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]
}
})
}
}
What is the correct way to define the types so that TypeScript can correctly handle the iteration process?