Skip to content Skip to sidebar Skip to footer

Object.keys Iteration Causing Typescript Error "element Implicitly Has An 'any' Type Because Index Expression Is Not Of Type 'number'"

I am trying to display the results of an API call that returns an object. In order to do a .map, I used Object.keys so that it will display the results. I'm learning new to Typescr

Solution 1:

Object.keys is badly typed and returns string[] instead of the key of the argument. Thus, crypto cannot be ensured to be a key of cryptos. One way to circumvent this is to cast Object.keys:

(Object.keys(cryptos) as keyof typeof cryptos).map(...)

Or, to just use Object.entries to iterate over both keys and values:

Object.entries(cryptos).map(([key, value], index) => (
    <likey={index}>
        {key}: {value}
    </li>
)

Post a Comment for "Object.keys Iteration Causing Typescript Error "element Implicitly Has An 'any' Type Because Index Expression Is Not Of Type 'number'""