Auto generated typescript interfaces issue

default discord avatar
tantalum1972last year

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

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

i have to use

( as User).id

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

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

Is there a nicer way to handle this?

  • default discord avatar
    angelok2741last year
  • default discord avatar
    tantalum1972last year

    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

  • @tantalum 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 =;
  • default discord avatar
    tantalum1972last year

    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


Chat on Discord



Can't find what you're looking for?

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