How to Use Fragment on Union Type in GraphQL
In GraphQL, to use a
fragment on a union type, you define inline fragments for each possible type within the union using ... on TypeName. This lets you query fields specific to each type in a single query.Syntax
When querying a union type, use inline fragments to specify fields for each possible type. The syntax is:
{
unionField {
... on TypeA {
fieldA1
fieldA2
}
... on TypeB {
fieldB1
fieldB2
}
}
}Here, unionField is the union type field. Each ... on TypeName block defines fields to fetch for that specific type.
graphql
{
unionField {
... on TypeA {
fieldA1
fieldA2
}
... on TypeB {
fieldB1
fieldB2
}
}
}Example
This example shows a query on a union type SearchResult that can be either Book or Author. The query fetches fields specific to each type.
graphql
query Search {
search(term: "GraphQL") {
... on Book {
title
pages
}
... on Author {
name
booksWritten
}
}
}Output
{
"data": {
"search": [
{
"title": "Learning GraphQL",
"pages": 350
},
{
"name": "John Doe",
"booksWritten": 5
}
]
}
}
Common Pitfalls
- Not using
... on TypeNameinside the union field causes errors because GraphQL needs to know which type's fields to fetch. - Trying to query fields directly on the union without fragments will fail.
- Forgetting to include all possible types in fragments may miss data.
graphql
query Wrong {
search(term: "GraphQL") {
title # Error: 'title' is not on union type directly
}
}
query Right {
search(term: "GraphQL") {
... on Book {
title
}
... on Author {
name
}
}
}Quick Reference
| Concept | Description |
|---|---|
| Union Type | A field that can return one of several object types. |
| Inline Fragment | Use ... on TypeName to specify fields for each type. |
| Fragment Usage | Required to query fields on union types because fields differ per type. |
| Error Cause | Querying union fields without fragments causes validation errors. |
Key Takeaways
Use inline fragments with
... on TypeName to query union types in GraphQL.Each fragment specifies fields for one possible type in the union.
Never query fields directly on the union without fragments.
Include all relevant types in your query to get complete data.
Fragments help GraphQL know which fields to fetch based on the actual type.