Enums
Enums can be defined a number of different ways:
-
Using typescript enums
-
Using an array of strings
Note that we use
as const
to allow ts to properly type our enum values. -
Using a values object:
Again we use
as const
here to allow the enum values to be correctly inferred. Theas const
can also be added to the values instead, or omitted if thevalues
are already 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 a values object also allows the name of the enum value to be different from the typescript value used internally in your resolvers.
The keys (eg
Southern
) are used as the name of the enum value in you GraphQL schema, and thevalue
(eg.'giraffa'
) property is used as the value you will receive in the arguments for your resolvers, or the value you need to return from your resolvers. This is similar to how typescript enum values can be assigned string or numeric values. -
Using an object with
as const
Modern TypeScript may prefer using objects with as const over enums to align with JavaScript standards. This approach essentially mirrors the "array of strings" method. You can use
Object.toEntries
andObject.fromEntries
to turn convert to Object values form described above.For more detailed information, you can refer to the TypeScript handbook on Objects vs Enums.
Alternatively, using
Object.keys
orObject.values
will allow you to produce an enum that uses just the keys or values of the object for both the internal typescript and name in the GraphQL schema.
Using Enum Types
Enums can be referenced 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: