Home > Net >  Object is of type 'unknown'.(2571) when using map() with array of objects
Object is of type 'unknown'.(2571) when using map() with array of objects

Time:11-11

Although I have googled this error and seen many posts about the topic, I still couldn't figure out how to fix the error.

I'm fetching some data through external API call that comes with the following signture

const properties: { [x: string]: unknown;} | { [x: string]: unknown;}[] | undefined

When I try to map the object with

const myMap = properties?.map((item: { [x: string]: unknown;} | { [y: string]: unknown;}) => { return { [item.x as string]: item.y } });

I got the a.m. typescript error at properties?.map

Am I missing a simple thing here? Appreciate any help

CodePudding user response:

properties can be an object or array of objects of undefined. You cannot use map on an object. So you get that error.

if you want to use Array.prototype.map, you could create another variable and make sure it is of type { [x: string]: unknown;}[] | undefined:

const arrayOfProperties = properties
  ? Array.isArray(properties)
    ? properties
    : [properties]
  : undefined;
  • Related