To define a GraphQL union, put a @gqlUnion docblock directly before a:

  • type alias of a union of object types;
  • type alias of a reference to a single object type (for a union with one member).

As with other tags, the name after the tag, if any, is the union's name in the schema, when it differs from the type's name.

User.ts
/**
 * A description of my union.
 * @gqlUnion
 */
type MyUnion = User | Post;

/** @gqlType */
class User {
  __typename = "User" as const;
  /** @gqlField */
  name: string;

  constructor(name: string) {
    this.name = name;
  }
}

/** @gqlType */
class Post {
  __typename = "Post" as const;
  /** @gqlField */
  content: string;

  /** @gqlField */
  author: User;

  constructor(content: string, author: User) {
    this.content = content;
    this.author = author;
  }
}

Note

Every type in the TypeScript union must be annotated with @gqlType. Gratos reminds you with a helpful error message if you forget.

Note

Gratos must be able to determine the typename of every member of a union. So it checks that every member type either defines a __typename property, typed as a string literal (__typename: "MyType") or set to one (__typename = "MyType" as const), or is an exported class. It uses either one to determine the typename at runtime.