1
  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.

enter image description here

1

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you kindly, sir, this is what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.