I have created a
media
collection and have a relation on my
posts
collection for a
featuredImage
field.
After generating types, I am seeing typescript complaining that
sizes
or
alt
(or anything on
featuredImage
for that matter) do no exist on type
number | Media
If I remove
number
from the generated types for the
featuredImage
property, it no longer complains. But I suspect this is not the correct approach, what am I missing?
// payload-types.ts
export interface Post {
id: number;
title: string;
featuredImage?: number | Media | null;
slug?: string | null;
content?: string | null;
updatedAt: string;
createdAt: string;
_status?: ('draft' | 'published') | null;
}
I'm using
3.0.0-beta.20
For reference, here is my
posts
collection:
import type { CollectionConfig } from 'payload/types';
import { slugifyPost } from './hooks/slugifyPost';
import { revalidatePosts } from './hooks/revalidatePosts';
import { revalidatePostsAfterDelete } from './hooks/revalidatePostsAfterDelete';
export const Posts: CollectionConfig = {
slug: 'posts',
admin: {
useAsTitle: 'title',
},
versions: {
drafts: true,
},
fields: [
{
name: 'title',
label: 'Title',
type: 'text',
required: true,
},
{
name: 'featuredImage',
label: 'Featured Image',
type: 'upload',
relationTo: 'media',
},
{
name: 'slug',
label: 'Slug',
type: 'text',
admin: {
position: 'sidebar',
},
hooks: {
beforeValidate: [slugifyPost],
},
},
{
name: 'content',
label: 'Content',
type: 'textarea',
},
],
hooks: {
afterChange: [revalidatePosts],
afterDelete: [revalidatePostsAfterDelete],
},
};
And here's my
media
collection:
import type { CollectionConfig } from 'payload/types';
export const Media: CollectionConfig = {
slug: 'media',
upload: {
staticDir: 'media',
imageSizes: [
{
name: 'card',
width: 600,
height: 400,
formatOptions: { format: 'webp', options: { quality: 90 } },
},
],
adminThumbnail: 'thumbnail',
mimeTypes: ['image/*'],
},
fields: [
{
name: 'alt',
type: 'text',
},
],
};
Is there a possibility my types aren't being correctly generated here?
you need to cast
featuredImage
to
Media
:
const image = post.featured_image as Media
depending on the
depth
you specify in your query,
feautured_image
could potentially just be a number, which obviously doesn't have any of the
Media
attributes
I think the typings aronud this can be improved but I'm not sure how
maybe worth creating a discussion on this
yeah, the existing typings make sense for the HTTP API. but with the local API, they could be context-aware wrt depth....might make sense to adjust in 3.0 since the local API is taking center stage
Thanks for the explanation
@794404091139719188, will keep an eye on that discussion too - thanks
@114557048678514693. Appreciate your guys help, error no longer present 🙂
Star
Discord
online
Get dedicated engineering support directly from the Payload team.