[英]Not able to use the Object.values function with an object in TypeScript
我正在尝试使用Object.values(obj)
function 创建 object 内所有键值的数组,但它会引发以下错误:
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:
{
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
作为 object 显式使用,但它没有用。 我尝试了一个简单的 for 循环解决方法,但这也不起作用。
data?.socialMedia
会给出undefined
如果data
是假的。 而Object.values()
期望 object 作为参数; 那就是你得到的错误。 你可以通过这样做来修复它:
{data ? (
Object.values(data.socialMedia).map((social) => (
<div key={social} className="cursor-pointer">
{renderSocial(social)}
</div>
))
) : (
<></>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.