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?