1

I am trying to iterate over the keys of a class using the forEach function

const foo = {
  a: 'hello',
  b: 'world',
}

Object.keys(foo).forEach(k => console.log(foo[k]))

However I get the error:

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

Using a suggestion I found on a different post I was able to fix this with

Object.keys(foo).forEach(k => console.log(foo[k as keyof typeof foo]))

However I don't understand why this is necessary? Is there no way for typesript to know that k will always be a key of foo?

1
  • 1
    See this and this for more information. Commented Nov 16, 2022 at 18:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.