我正在使用 Astro 和 Contentful 来制作博客。我有一个名为
author
的内容类型,它有 3 个字段。
姓名 | 字段类型 |
---|---|
全名 | 短文 |
爆头 | 媒体 |
生物 | 富文本 |
我正在创建一个列出所有作者的组件。我的代码如下所示:
---
import { contentfulClient } from "../lib/contentful";
import { documentToHtmlString } from "@contentful/rich-text-html-renderer";
import type { Asset, EntryFieldTypes } from "contentful";
interface Author {
contentTypeId: "author",
fields: {
fullName: EntryFieldTypes.Text,
headshot: EntryFieldTypes.AssetLink,
bio: EntryFieldTypes.RichText
}
}
const authors = await contentfulClient.getEntries<Author>({
content_type: "author"
})
---
<h1>Authors</h1>
{
authors.items.map((author) => (
<p>{author.fields.fullName}</p>
<img src={`https:${(author.fields.headshot as any).fields.file.url}`} alt="" srcset="">
))
}
这可行,但我必须将
author.fields.headshot
转换为 any
,因为打字稿抱怨 fields
不是爆头的属性。我的智能感知只能找到 sys
作为 headshot
的属性。
所以这个:
<img src={`https:${author.fields.headshot.fields.file.url}`} class="w-full max-w-48" alt="" srcset="">
在本地工作。但是当我部署到 Netlify 时,构建失败,因为 typescript 无法编译。我的解决方案有效,但感觉很危险。我想也许我在
EntryFieldTypes
界面中使用了错误的 Author
属性,但 AssetLink
似乎是最合适的。
我相信您的头像字段应该是
Asset
类型,而不是 AssetLink
类型,这是富文本结构中的链接。
headshot: Asset,