interface ColorThemes {
DEFAULT: string,
DARK: string,
}
const colorThemes: ColorThemes = {
DEFAULT: "default",
DARK: "dark",
}
return (
<div>
{Object.keys(colorThemes).map(key =>
<div>{colorThemes[key]}</div>
)}
</div>
)
I'm trying to loop through an enum of strings. But visual studio intellisense complains and says:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'xxx'.
No index signature with a parameter of type 'string' was found on type 'xxx'.
Any help would be appreciated.
Object.keys(colorThemes) gives you a list of strings, but at colorThemes[key] the key must be a ColorThemes-key, not just any string.
But because you know for sure that every key is always a key of colorThemes, you can tell Typescript to assume that:
<div>
{Object.keys(colorThemes).map(key =>
<div>{colorThemes[key as keyof ColorThemes]}</div>
)}
</div>