Type systems fall into two categories: structural and nominal. In a structural type system, two types are equivalent if they have the same structure, or shape. In a nominal type system, two types are equivalent if they have the same name. For example:

  • TypeScript is structurally typed;
  • GraphQL is nominally typed.

This mismatch is a challenge for Gratos, which lets you express nominal GraphQL types with structural TypeScript constructs.

To illustrate the problem, consider this example:

structural-author.ts
/** @gqlType */
type User = {
  /** @gqlField */
  name: string;
};

/** @gqlType */
type Post = {
  /** @gqlField */
  author: { name: string };
};

In TypeScript, Post.author is a valid User, since the type literal { name: string } has the same structure as the User type. But to build the GraphQL definition of Post, we need the name of Post.author's type.

Gratos' solution

Gratos gets around this by requiring that any type annotation it reads as a GraphQL type be a direct reference to a declaration. That declaration can be a type alias, an interface or a class, but it must be a declaration. Otherwise, Gratos reports a (hopefully helpful) error: here, that it does not expect a type literal.

To correct the error above, we can write:

Post.ts
/** @gqlType */
type User = {
  /** @gqlField */
  name: string;
};

/** @gqlType */
type Post = {
  /** @gqlField */
  author: User;
};

When Gratos infers the type of Post.author, it asks TypeScript for the declaration of the type User, where the type User is defined. From it, Gratos "sees" the @gqlType tag, and knows exactly which nominal GraphQL type is referenced.

This works out well, since the TypeScript library does not expose a way to check whether two types are compatible as far as TypeScript is concerned (structurally equivalent), but it does expose a way to find the declaration of a type.

Limitations imposed

So some things that feel intuitive to write in TypeScript cannot be understood by Gratos. Gratos knows these cases and tries to report helpful errors when it meets them.

For example, you cannot use an intermediate type alias, since the definition of the Admin type is not annotated as a GraphQL type:

structural-alias.ts
/** @gqlType */
type User = {
  /** @gqlField */
  name: string;
};

type Admin = User;

/** @gqlType */
type Post = {
  /** @gqlField */
  author: Admin; // <-- Gratos cannot infer the name of this type
};