Why is my generated type for my media collection possibly 'string'?

default discord avatar
alexr-io
7 months ago
6

Hi, I have the following field on my collection:


   {
      name: 'heroImage',
      type: 'upload',
      relationTo: 'media',
      admin: {
        condition: (_, siblingData) =>
          siblingData.showHero && !siblingData.makeSlider,
      },
    },


In my generated types, this field is defined as

string | Media

. Now, I understand the Media type, as this is just the generated type for the relation on this field, but I don't understand how it could possibly be string. Just wondering what cases I might need to handle where this field may be string?

  • default discord avatar
    Jarrod
    7 months ago

    @alexr-io set

    depth

    to 0 and then query a document in your collection



    /api/collection-slug/id?depth=0

  • default discord avatar
    alexr-io
    7 months ago

    Perfect explanation, thank you

  • default discord avatar
    nickfday
    5 months ago

    @Jarrod Encountered the same issue. Makes sense. Is there a rule I can set tsconfig to stop my editor complaining?



    property 'url' does not exist on type 'string | Media'.


    Property 'url' does not exist on type 'string'.ts(2339

  • default discord avatar
    Jarrod
    5 months ago

    It’s not really an error though. It could be a string, so the TS error is accurate. Maybe you’ll find some helpful info here:

    https://discord.com/channels/967097582721572934/1061947681448153188
  • default discord avatar
    thgh
    5 months ago

    use typeof x === 'string' ? '' : x.url

  • default discord avatar
    nickfday
    5 months ago

    Thanks I've just extended the interface otherwise I have to add a lot of ternary's

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.