I am using the auto generated types from Payload and a media collection for several upload fields. As I am typing my component props the media properties like e.g. "icon" is typed as string | Media which leads to error when referring to Media attributes like icon.filename because that does not exist on strings of course. It's a pain to cast all of the media types to be Media. To me the typing does not make sense so I am questioning if the mistake is on my side or there is a good reason for it to be string | Media.
autogenerated from payload-types.
export interface Header {
id: string;
logo?: string | Media;
}
Hi @chris_heinz,
That is not a mistake on your part. We have had a lot of discussion around the best way to type relationships and uploads. The complication here is that when a document is read the population is dynamic based on the
depth
parameter. Since there are times when the depth is 0, you can expect to get a string with the
id
instead of the Media object.
There have been some ideas come out about how this could be improved in Github discussions.
https://github.com/payloadcms/payload/discussions/1563
I added a link if you're interested in that, several comments talk about workaround to the depth problem.
Oh and one other reason that a relationship or upload can be a string is because of access control. Suppose a user can read a parent document but is not allowed
read
access to the related doc. That relationship will not be populated and is left as a string.
Alright I already thought that this (edit: depth) might be the reason for it. I will give it a read later that day and hopefully I ll come up with a better solution than type casting it in the frontend. Thank you a lot for the explanation @dribbens
You're welcome @chris_heinz. We're always looking for ways to improve so please share in on the discussion if you have new insight.
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.