Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Auto generated typescript interfaces issue

default discord avatar
tantalum19722 years ago
4

When I autogenerate the interfaces, relation fields are typed as entity OR string, and this is correct, since I may be getting an ID or the actual entity, for example:



author: string | User;


While this is technically correct, when I try to work with the data, for example get the author ID, I cannot use



entity.author.id


when I try to do that I get an error stating that "string" does not have an ID property. This error message is correct as the author field might be a string



However, this forces some ugly code, as instead of



entity.author.id


i have to use



(entity.author as User).id


and this issue componds as I go deeper into the data, for example:



((entity.author as User).media as Media).url


Is there a nicer way to handle this?

  • default discord avatar
    angelok27412 years ago
  • default discord avatar
    tantalum19722 years ago

    Thanks, so I'm guessing my solution would be to remove the "string | " part from the generated file, fix it every time I regenerate (as the compiler would definitely remind me) - and wait until the fix is released... I can do that 🙂



    Thanks again

  • discord user avatar
    jarrod_not_jared
    2 years ago
    @1004634747105972225

    you could use a typeguard to ease your pains as well, something like this:



    // this function could be adjusted as you see fit
    export function isExpandedDoc<T>(doc: any): doc is T {
      if (typeof doc === 'object') return true;
      return false;
    }
    
    function YourFunction(user: User | string) {
      if (isExpandedDoc<User>(user)) {
        // expanded object can now be used
        const userID = user.id;
      }
    }
  • default discord avatar
    tantalum19722 years ago

    This is nice, I'll keep it in mind. In my use case, some of these documents go directly to template bindings, so I'd rather not have extra code, but it will sure come in handy in other use cases. Thank you again 🙂

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.