Skip to main content

Enums

GraphQL enums can be defined by placing a @gqlEnum docblock directly before a:

  • TypeScript enum declaration
  • Type alias of a union of string literals
  • Type alias deriving from a const array ((typeof X)[number]) or const object ((typeof X)[keyof typeof X])
/**
* A description of my enum.
* @gqlEnum <optional name of the enum, if different from type name>
*/
enum MyEnum {
/** A description of my variant */
OK = "OK",
/** A description of my other variant */
ERROR = "ERROR",
}

Note that the values of the enum are used as the GraphQL enum values, and must be string literals.

To mark a variants as deprecated, use the @deprecated JSDoc tag directly before it:

/** @gqlEnum */
enum MyEnum {
OK = "OK"
/** @deprecated Please use OK instead. */
OKAY = "OKAY"
ERROR = "ERROR"
}

We also support defining enums using a union of string literals, however there are some limitations to this approach:

  • You cannot add descriptions to enum values
  • You cannot mark enum values as deprecated

This is due to the fact that TypeScript does not see JSDoc comments as "attaching" to string literal types.

/** @gqlEnum */
type MyEnum = "OK" | "ERROR";

Runtime-accessible enums

If you need runtime access to enum values without using TypeScript's enum syntax, Grats supports deriving enums from const arrays and const objects.

info

The const declaration must be the immediately preceding statement before the @gqlEnum type alias. This ensures the actual list of enum values are colocated with the @gqlEnum annotation.

Const array

const ALL_STATUSES = ["DRAFT", "PUBLISHED", "ARCHIVED"] as const;

/** @gqlEnum */
type Status = (typeof ALL_STATUSES)[number];
Playground

Like union-of-literal enums, const arrays do not support descriptions or @deprecated on individual values. Use a const object or TypeScript enum if you need those.

Const object

Const objects allow you to define human-readable keys that map to GraphQL enum values, similar to TypeScript enum declarations. Unlike arrays, object properties support descriptions and @deprecated tags:

const Status = {
/** Currently being edited */
Draft: "DRAFT",
/** Available to readers */
Published: "PUBLISHED",
/** @deprecated Use DRAFT instead */
Hidden: "HIDDEN",
} as const;

/** @gqlEnum */
type Status = (typeof Status)[keyof typeof Status];
Playground