Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'." mean?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading