0
0
GraphqlConceptBeginner · 3 min read

What is Union Type in GraphQL: Explanation and Examples

In GraphQL, a union type allows a field to return one of several different object types, but not a combination of them. It is useful when a query can return different types of objects under the same field, letting clients handle varied results flexibly.
⚙️

How It Works

A union type in GraphQL is like a box that can hold one of several different types, but only one at a time. Imagine you have a mailbox that can receive letters, postcards, or packages, but never all mixed together in one slot. Similarly, a union type lets a field return either one type or another, depending on the data.

This is different from an interface because a union type does not require the types to share any fields. It simply groups multiple types together so the client knows the possible types it might receive. When querying, the client can check which type was returned and handle it accordingly.

💻

Example

This example shows a union type called SearchResult that can be either a Book or an Author. The query returns a list of search results that can be mixed types.

graphql
union SearchResult = Book | Author

type Book {
  id: ID!
  title: String!
  pages: Int!
}

type Author {
  id: ID!
  name: String!
  booksWritten: Int!
}

type Query {
  search(term: String!): [SearchResult!]!
}

# Example query
query {
  search(term: "GraphQL") {
    ... on Book {
      title
      pages
    }
    ... on Author {
      name
      booksWritten
    }
  }
}
Output
[ { "title": "Learning GraphQL", "pages": 350 }, { "name": "Alex Developer", "booksWritten": 5 } ]
🎯

When to Use

Use a union type when a field can return different object types that do not share the same fields. For example, a search feature might return results that are books, authors, or publishers. Since these types have different fields, a union type lets you group them without forcing a shared structure.

This helps keep your schema flexible and your queries clear, allowing clients to handle each type specifically. It is especially useful in APIs where responses can vary widely depending on the query or data source.

Key Points

  • A union type groups multiple object types but returns only one at a time.
  • It differs from interfaces because types in a union do not need to share fields.
  • Clients use inline fragments to handle each possible type in queries.
  • Ideal for fields that can return different types of results, like search or notifications.

Key Takeaways

Union types let a field return one of several different object types in GraphQL.
They are useful when returned types do not share common fields.
Clients use inline fragments to query fields specific to each type in the union.
Use union types to keep your API flexible for varied response types.