【发布时间】:2021-10-19 06:26:49
【问题描述】:
在 TypeScript/React 中映射对象时,我无法转换正确的类型。
我收到以下错误:“对象”类型上不存在属性“urls”。 TS2339
我能够解决此问题的唯一方法是设置任何,我意识到这是糟糕的糟糕。
我尝试使用对象中存在的属性创建一个接口,但这不起作用。
我是 TypeScript 的新手,所以任何帮助都会很棒。谢谢!
{images.map((image: object, key: number) => (
<Image
imageDesktop={image.urls.regular}
imageMobile={image.urls.small}
description={image.alt_description}
author={image.user.name}
url={image.links.html}
/>
))}
# Tried useing this Interface to set type to replace object, but got this error:
Argument of type '(image: ImageType, key: number) => JSX.Element' is not assignable to parameter of type '(value: object, index: number, array: object[]) => Element'.
Types of parameters 'image' and 'value' are incompatible.
Type '{}' is missing the following properties from type 'ImageType': urls, alt_description, user, links TS2345
interface ImageType {
urls: {
regular: string;
small: string;
};
alt_description: string;
user: {
name: string;
};
links: {
html: string;
};
}
【问题讨论】:
-
“我尝试使用对象中存在的属性创建一个接口,但这不起作用。”请详细说明这一点。为什么它不起作用?您看到了什么样的错误?
-
我看到了
url的属性,但没有看到urls的属性。 -
在这种情况下不要使用
object类型。使用Record<string, unknown> -
@AlexandervanOostenrijk 我将此添加到我的问题中,谢谢:)
-
@captain-yossarian 这是我尝试你的想法时遇到的错误:'(image: Record
, key: number) => JSX.Element' 类型的参数不是可分配给“(值:对象,索引:数字,数组:对象 [])=> 元素”类型的参数。参数 'image' 和 'value' 的类型不兼容。类型 'object' 不可分配给类型 'Record '。类型“{}”中缺少索引签名。 TS2345 102 |动画=“显示” 103 | > > 104 | {images.map((image: Record , key: number) => (
标签: typescript typeerror typescript-typings react-typescript