我在使用 Contentul 时遇到了 Typescript 问题。我希望有人能指出我正确的方向。
Contentful 根据我在 Contentful 中设置的内容类型为我生成了以下类型接口。
import type { ChainModifiers, Entry, EntryFieldTypes, EntrySkeletonType, LocaleCode } from "contentful";
export interface TypeBlendFields {
title: EntryFieldTypes.Symbol;
description: EntryFieldTypes.RichText;
cover: EntryFieldTypes.AssetLink;
}
export type TypeBlendSkeleton = EntrySkeletonType<TypeBlendFields, "blend">;
export type TypeBlend<Modifiers extends ChainModifiers, Locales extends LocaleCode> = Entry<TypeBlendSkeleton, Modifiers, Locales>;
使用
client.getEntries()
时,JSON 对象包含所需的所有数据,包括 cover
属性和所有嵌套属性(图像的元数据、系统和字段)。
我的问题是 Typescript 不知道
cover
的这些嵌套属性的类型。但我无法理解为什么。
我尝试创建以下界面
export interface ICover {
fields: {
title: string,
file: {
fileName: string,
contentType: string,
details: {
image: {
width: number,
height: number
},
size: number
},
url: string
},
description: string
}
}
并使用它
export interface TypeBlendFields {
title: EntryFieldTypes.Symbol;
description: EntryFieldTypes.RichText;
cover: EntryFieldTypes.AssetLink;
}
我能够使用没有点符号的属性,就像这样
newEntries[0].fields!['file']['url']
,但我想在这里使用正确的 Typescript。
任何帮助将非常感激。
没关系...我的界面
ICover
是正确的,但我没有正确使用它。
因此,当循环 JSON 响应对象时,可以将 Contentful
item
转换为特定类型(或接口)。就我而言,就像这样。
const entries = items.map(entry => {
return entry.fields.cover as ICover
}
我希望这可以帮助任何处理同样问题的人。
您在这里找到更好的解决方案了吗?在尝试使用自动生成的类型时,我遇到了类似的问题。