Enums, Interfaces and Unions

GraphQL provides several type-system features for modeling domains that are more complex than simple objects.

Enums

An enum restricts a value to a predefined set of named values.

enum OrderStatus {
  PENDING
  CONFIRMED
  SHIPPED
  DELIVERED
  CANCELLED
}

This is preferable to accepting arbitrary strings when the domain has a known finite set of states.

Interfaces

An interface defines a set of fields that implementing object types must provide.

interface Node {
  id: ID!
}

type User implements Node {
  id: ID!
  name: String!
}

type Product implements Node {
  id: ID!
  name: String!
}

Interfaces are useful when multiple object types share a common contract.

Unions

A union represents a value that may be one of several object types without requiring those types to share fields.

union SearchResult = User | Product | Article

A client querying a union usually needs fragments to select fields specific to the concrete type.

search(term: "graphql") {
  ... on User {
    id
    name
  }
  ... on Product {
    id
    name
    price
  }
}

The distinction is important:

  • Interface: different types share a defined field contract.
  • Union: different types are grouped as possible result types, but the union itself does not require shared fields.
Advanced GraphQL Types
Enum: Finite set of named values
Useful for states, categories, roles, and other constrained values.
Interface: Shared field contract
Multiple object types implement the same required fields.
Union: One of several object types
Groups possible object types without imposing a shared field contract.
Key Takeaways
  • Enums constrain values to predefined names.
  • Interfaces define shared fields across implementing object types.
  • Unions represent one of several possible object types.
  • Inline fragments are commonly used when querying unions and interfaces.
Knowledge Check

What is the main difference between an interface and a union?