I'm using Astro and Contentful to make a blog. I have a content type called author which has 3 fields.
| Name | Field Type |
|---|---|
| Full Name | Short text |
| Headshot | Media |
| Bio | Rich Text |
I'm working on creating a component that will list out all the authors. My code looks as follows:
---
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="">
))
}
This works but I had to cast author.fields.headshot as any because typescript was complaining that fields wasn't a property of headshot. And my intellisense could only find sys as a property of headshot.
So this:
<img src={`https:${author.fields.headshot.fields.file.url}`} class="w-full max-w-48" alt="" srcset="">
Does work locally. But when I go to deploy to Netlify the build fails since typescript won't compile. My solution works but it feels dangerous. I thought maybe I was using the wrong EntryFieldTypes property in my Author interface but AssetLink seems to be the most appropriate.
I believe your headshot field should be of type
AssetnotAssetLinkwhich is a link within a rich text structure.