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

Time:03-28

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

Straight to the example, I have data that looks like that:

const earthData = {
  distanceFromSun: 149280000,
  continents: {
    asia: {area: 44579000, population: 4560667108},
    africa: {area: 30370000, population: 1275920972},
    europe: {area: 10180000, population: 746419440},
    america: {area: 42549000, population: 964920000},
    australia: {area: 7690000, population: 25925600},
    antarctica: {area: 14200000, population: 5000}
  }
}

I want to create a new object in which keys are continents names, and values are areas. I can easily do the following and it works well:

const outputWorks = Object.fromEntries(Object.entries(earthData.continents).map( ([k, o]) => [k, o.area] ))
// {
//   "asia": 44579000,
//   "africa": 30370000,
//   "europe": 10180000,
//   "america": 42549000,
//   "australia": 7690000,
//   "antarctica": 14200000
// } 

By contrast, a very similar code doesn't work when the same input data is a result of a different operation.

const solarSystem = {
  mercury: {},
  venus: {},
  earth: { // earth entry is just like `earthData` object
    distanceFromSun: 149280000,
    continents: {
      asia: { area: 44579000, population: 4560667108 },
      africa: { area: 30370000, population: 1275920972 },
      europe: { area: 10180000, population: 746419440 },
      america: { area: 42549000, population: 964920000 },
      australia: { area: 7690000, population: 25925600 },
      antarctica: { area: 14200000, population: 5000 },
    },
  },
  mars: {},
  jupiter: {},
  saturn: {},
  uranus: {},
  neptun: {},
};
const earthDataExtracted = Object.values(solarSystem)[2] as any; // again, this is the same as `earthData` 

So why does the following throw an error?

Object.fromEntries(Object.entries(earthDataExtracted.continents).map( ([k, o]) => [k, o.area] ))
//                                                                                    ^

(parameter) o: unknown
Object is of type 'unknown'.(2571)

See here for TS playground

And even more strangely, on my own machine (VSCode) the error is different:

Property 'area' does not exist on type 'unknown'.ts(2339)

Is there a simple thing I'm missing here?

CodePudding user response:

To resolve the issue, you need to either provide a type for earthDataExtracted.continents (but if I understand correctly your discussion with @jcalz, it not that easy), or simply declare it as any:

Object.fromEntries(Object.entries(earthDataExtracted.continents).map( ([k, o]: [string, any]) => [k, o.area] ))
  • Related