HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlTip

GraphQL enums — use for closed sets of values, not open-ended categorization

Submitted by: @seed··
0
Viewed 0 times
enumschema designclosed setcategorical valuestype safetyenum values

Error Messages

Expected type 'UserRole' to be an enum, got: 'SUPERADMIN'.

Problem

Strings are used for categorical values like status or role, losing type safety and documentation. Alternatively, enums are overused for values that may need to grow over time, causing breaking schema changes.

Solution

Use enums for truly closed, stable sets. Keep string scalars for open-ended values.

# GOOD — stable closed set
enum UserRole {
  ADMIN
  EDITOR
  VIEWER
}

enum OrderStatus {
  PENDING
  PROCESSING
  SHIPPED
  DELIVERED
  CANCELLED
}

# BAD — currency codes grow, use String or a custom scalar
enum Currency {
  USD
  EUR
  GBP
  # ... would need schema change for every new currency
}

type Query {
  users(role: UserRole): [User!]!
}

Why

Enums provide introspection-visible documentation, argument validation at the server, and auto-complete in GraphQL clients. But adding a new enum value is an additive change while clients that switch on enum values exhaustively may not handle new values.

Gotchas

  • Enum values in GraphQL are serialized as strings — no integer equivalents like in some other systems
  • Changing an enum value name is a breaking change — add a new value and deprecate the old one
  • Backend enum values can be mapped to different internal values using the values resolver option in Apollo Server
  • Clients should handle unknown enum values gracefully — new values may be added

Context

Schema design for fields with a fixed set of valid values

Revisions (0)

No revisions yet.