I'm trying to iterate over the keys of an object that has an interface, but TypeScript does not recognise 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]
}
})
}
}
How should I type it so Typescript will understand the iteration?