【问题标题】:Not able to use the Object.values function with an object in TypeScript无法将 Object.values 函数与 TypeScript 中的对象一起使用
【发布时间】:2022-11-14 00:43:46
【问题描述】:

我正在尝试使用 Object.values(obj) 创建对象内所有键的值数组 函数,但它会引发以下错误:

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)

这是带有对象类型的代码:

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

我尝试明确使用 data.?socialMedia 作为对象,但它没有用。我尝试了一个简单的 for 循环解决方法,但这也不起作用。

【问题讨论】:

标签: javascript reactjs typescript next.js


【解决方案1】:

如果data 是假的,data?.socialMedia 将给出undefined。而Object.values() 期望一个对象作为参数;这就是你得到的错误。您可以这样做来修复它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 2017-02-08
    • 2020-09-11
    • 2017-06-07
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2017-09-27
    相关资源
    最近更新 更多