Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Iterating over the interface fields does not work

Tags:

typescript

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?

like image 326
StragaSevera Avatar asked May 18 '26 09:05

StragaSevera


1 Answers

Yes, Object.keys() returns string[] and this is intentional https://github.com/Microsoft/TypeScript/issues/12870

(Object.keys(newResources) as Array<keyof Resources>).forEach(...) for the rescue.

UPD

(Object.keys(newResources) as Array<keyof typeof newResources>).forEach(...) also helps.

like image 103
sneas Avatar answered May 20 '26 02:05

sneas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!