Join us on Nov 7 for GraphQL Summit Virtual
Join API innovators, GraphQL experts, and AI trailblazers on Nov 7 at GraphQL Summit Virtual. Register for free →
When we need to constrain a field to return just one option from a set that we've defined, we can use the enumeration type—known more casually as an enum!
An enum is a structure that contains a number of different options. It won't accept just any value—instead, we restrict fields that return an enum type to always return one of the enum's options. Otherwise, they're invalid!
Let's look at an enum type that we could apply to fruits.
enum SeasonEnum {FALLWINTERSPRINGSUMMER}
Note: By convention, we write our enum's possible values in
SCREAMING_SNAKE_CASE
.
The SeasonEnum
type contains just four options—and we can see why! When discussing the different seasons in a year, only these four choices are valid options.
Applied to a Fruit
type, we can use the SeasonEnum
as a field's return type.
type Fruit {id: ID!name: String!seasonWhenRipe: SeasonEnum!}
The seasonWhenRipe
field that we've added to the Fruit
type specifies that when we query for different kinds of fruit and their ripest seasons, the value we get back for each will be one of the following: FALL
, WINTER
, SPRING
, or SUMMER
.
Try it out with the query below!
Up Next: Interfaces & Unions
About
GraphQL.com is maintained by the Apollo team. Our goal is to give developers and technical leaders the tools they need to understand and adopt GraphQL.
GraphQL.com 2024