To define a GraphQL interface, put a @gqlInterface docblock directly before an interface declaration. As with other tags, the name after the tag, if any, is the interface's name in the schema:

MyClass.ts
/**
 * A description of my interface.
 * @gqlInterface MyInterfaceName
 */
interface MyClass {
  /** @gqlField */
  someField: string;
}

Shared field implementation

To define a field with one implementation shared by every implementor, use the function style of @gqlField. The field is added to every implementor of the interface.

Greetable.ts
/** @gqlInterface */
interface Greetable {
  /** @gqlField */
  name: string;
}

/** @gqlField */
export function greeting(thing: Greetable): string {
  return `Hello ${thing.name}!`;
}

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

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

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

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

Types implementing interfaces

To declare that a type implements an interface, see Implementing interfaces on the Types page.

Interfaces implementing interfaces

To declare that an interface implements another interface, use TypeScript's extends keyword:

User.ts
/** @gqlInterface */
interface Person {
  /** @gqlField */
  name: string;
}

/** @gqlInterface */
interface User extends Person {
  /** @gqlField */
  name: string;

  /** @gqlField */
  username: string;
}

Note

Each implementor of an interface must define every field the interface requires with /** @gqlField */. So an implementor of an interface that implements another interface must define the fields both interfaces require.

Merged interfaces

TypeScript merges interfaces when you define several interfaces with the same name in the same scope. For example, Node is a built-in interface that describes DOM nodes, so a top-level Node interface of your own is merged with the built-in one when TypeScript treats its file as a global script (typically a file with no import or export, depending on your module settings). In a module, your Node shadows the built-in one instead, and needs no rename: this site's own Node interface is declared that way.

To avoid ambiguity, Gratos reports an error when a GraphQL interface is defined with a merged TypeScript interface. To avoid the error, define an interface with a unique name, and rename it to the name you want in your schema:

GqlNode.ts
import type { ID } from "gratos";

/** @gqlInterface Node */
interface GqlNode {
  /** @gqlField */
  id: ID;
}