0

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 code, with the type of object:

{
  Object.values(data?.socialMedia).map((social) => (
    <div key={social} className="cursor-pointer">
      {renderSocial(social)}
    </div>
  ));
}
export type SocialMedia = {
  fb: string;
  insta: string;
  twitter: string;
};

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.

2

1 Answer 1

1

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>
  ))
) : (
  <></>
)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.