Home > database >  What does "Element implicitly has an 'any' type because expression of type 'stri
What does "Element implicitly has an 'any' type because expression of type 'stri

Time:01-13

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.

CodePudding user response:

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[]

  • Related