How to solve forEach loop element implicitly has an `any` type TypeScript error
Have you ever tried iterate an object by using Objects.keys()
with TypeScript, and do you get this error:
const response = {
a: 1,
b: 2,
c: 3,
};
Object.keys(response).forEach(key => {
console.log(response[key])
});
Element implicitly has an 'any' type because expression of type 'string' can't be used to index
The best way to get around this issue is to create your Object.keys()
function!
Here’s how to create one:
const objectKeys = <Obj>(obj: Obj): (keyof Obj)[] => {
return Object.keys(obj) as (keyof Obj)[];
}
// No implicitly has. `any` type errors
objectKeys(response).forEach(keys => {
console.log(response[keys])
})
All we’re doing with the newly created function, objectKeys()
is returning the keys of the response
object as a type.
So instead of keys being a string type, they’re now a
, b
, or c
(keys from the response
object.
I like to tweet about code and post helpful code snippets. Follow me there if you would like some too!