0
const foo = {};

['bar', 'baz'].forEach((word) => {
    foo[word] = []
});

The above gives me the following error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.

How do I fix this? You can try it here:

https://www.typescriptlang.org/play?ssl=5&ssc=4&pln=1&pc=1#code/MYewdgzgLgBAZiEMC8MDeBfA3AKBwbQHIAjAQwCdCAaGE0gL0IF0A6BcgUVOAAsAKPgHcQ5ACYBKFAD50OGPPiJ8wsUxQx8THBnFYgA.

Animal Rights
  • 9,107
  • 6
  • 28
  • 40
  • This has been answered several times on StackOverflow, for example [here](https://stackoverflow.com/questions/57350092/string-cant-be-used-to-index-type), [here](https://stackoverflow.com/questions/56568423/typescript-no-index-signature-with-a-parameter-of-type-string-was-found-on-ty), and [here](https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b). – Zac Anger Jan 13 '23 at 05:38
  • 1
    I read some of those and still didn't understand, hence why I asked. The answer below is perfect. – Animal Rights Jan 13 '23 at 05:47

1 Answers1

2

Since your object seems to have dynamic keys, you should specify it in the type of foo.

The solution for your particular case would be


const foo : {
    [key: string]: string[] // whatever type of array
} = {};

['bar', 'baz'].forEach((word) => {
    foo[word] = []
});

This tells that foo is a type of object which takes in keys of type string and the corresponding type of value for it will be string[]

May Rest in Peace
  • 2,070
  • 2
  • 20
  • 34