Enums

Defining Enum Types

Enums can be defined a number of different ways:

  1. Using typescript enums

export enum Diet {
HERBIVOROUS,
CARNIVOROUS,
OMNIVORIOUS,
}
builder.enumType(Diet, {
name: 'Diet',
});
  1. Using an array of strings

export const LengthUnit = builder.enumType('LengthUnit', {
values: ['Feet', 'Meters'] as const,
});

Note that we use as const to allow ts to properly type our enum values.

  1. Using a values object:

export const GiraffeSpecies = builder.enumType('GiraffeSpecies', {
values: {
Southern: {
description: 'Also known as two-horned giraffe',
value: 'giraffa',
},
Masai: {
value: 'tippelskirchi',
},
Reticulated: {
value: 'reticulata',
},
Northern: {
value: 'camelopardalis',
},
} as const,
});

Again we use as const here to allow the enum values to be correctly inferred. The as const can also be added to the values instead, or omitted if the values already are defined using a variable that typescript can type correctly.

Using a values object like this enables defining additional options like a description for each enum value.

Using Enum Types

Enums can be references either by the Ref that was returned by calling builder.enumType or by using the typescript enum. They can be used either as arguments, or as field return types:

builder.objectFields('Giraffe', (t) => ({
height: t.float({
args: {
unit: t.arg({
type: LengthUnit,
required: true,
defaultValue: 'Meters',
}),
},
resolve: (parent, args) =>
args.unit === 'Meters' ? parent.heightInMeters : parent.heightInMeters * 3.281,
}),
diet: t.field({
description:
'While Giraffes are herbivores, they do eat the bones of dead animals to get extra calcium',
type: Diet,
resolve: () => Diet.HERBIVOROUS,
}),
species: t.field({
type: GiraffeSpecies,
resolve: () => 'camelopardalis' as const,
}),
}));