Object is of type 'unknown' - forEach and map

Viewed 3885

I am doing a loop on an Object using forEach or map. However, I am getting a type error on the variable that I use to loop. The error is Object is of type 'unknown'.

This occurs on val.name, val.title.

With .forEach

    Object.entries(data).forEach(
      ([, val]) => {
        newObject[val.name] = { // Object is of type 'unknown'
          title: val.title // Object is of type 'unknown'
        }}
      )

With .map

Object.entries(data).map(
  ([, val]) => {
    newObject[val.name] = { // Object is of type 'unknown'
      title: val.title // Object is of type 'unknown'
    }}
  )

I tried to specify a type on the variable val such as:

([, val: any]) => {..my code..}

but it does not accept a type in that position

1 Answers

One answer is to go back to the "classic" way of iterating object properties in JavaScript, before Object.entries() existed, like so:

const obj = {
  a: 1,
  b: 2,
  c: 3,
}
for (const key of Object.keys(obj)) {
  const value = obj[k]
  // Do something with 'value'...
}

This works because the type of value is any instead of the much more restrictive unknown that comes from using Object.entries(). This was tested and works in TypeScript v4.

Related