Home > Net >  Not able to use the Object.values function with an object in TypeScript
Not able to use the Object.values function with an object in TypeScript

Time:11-10

I'm trying to make an array of values of all the keys inside an object using the Object.values(obj) function but it throws the following error:

No overload matches this call.
  Overload 1 of 2, '(o: { [s: string]: string; } | ArrayLike<string>): string[]', gave the following error.
    Argument of type 'SocialMedia | undefined' is not assignable to parameter of type '{ [s: string]: string; } | ArrayLike<string>'.
      Type 'undefined' is not assignable to type '{ [s: string]: string; } | ArrayLike<string>'.
  Overload 2 of 2, '(o: {}): any[]', gave the following error.
    Argument of type 'SocialMedia | undefined' is not assignable to parameter of type '{}'.
      Type 'undefined' is not assignable to type '{}'.ts(2769)

Here is the screenshot of the code, with the type of object:

I tried using explicitly using the data.?socialMedia as an object but it didn't work. I tried a workaround with a simple for loop but that does not work either.

CodePudding user response:

data?.socialMedia would give undefined if data is falsy. And Object.values() expect an object as a parameter; that's the error you are getting. You could fix it by doing so:

{data ? (
  Object.values(data.socialMedia).map((social) => (
    <div key={social} className="cursor-pointer">
      {renderSocial(social)}
    </div>
  ))
) : (
  <></>
)}
  • Related