Introduction
Union types let you combine different object types into one. This helps when a field can return different kinds of data.
Jump into concepts and practice - no test required
Union types let you combine different object types into one. This helps when a field can return different kinds of data.
union SearchResult = Book | Author | Magazine
union Media = Photo | Video
union SearchResult = User | Post | Comment
This example defines a union SearchResult that can be a Book or an Author. The query searches and handles both types separately.
type Book {
title: String
author: String
}
type Author {
name: String
books: [Book]
}
union SearchResult = Book | Author
# Query example
query {
search(keyword: "GraphQL") {
... on Book {
title
author
}
... on Author {
name
}
}
}When querying a union type, use inline fragments (... on TypeName) to access fields of each type.
Union types cannot have fields themselves; only the member types have fields.
Union types group multiple object types into one.
Use unions when a field can return different object types.
Query unions with inline fragments to get data from each type.
union types in GraphQL?SearchResult that includes User and Post types?union Name = Type1 | Type2 with pipe separators.SearchResult = User | Post and this query:{ search { ... on User { name } ... on Post { title } } }name from User and title from Post.union SearchResult = User | Post
{ search { ... on User { id name } ... on Post { id title } } }email inside Post inline fragment like this:{ search { ... on User { id name } ... on Post { id title email } } }email is not defined on Post type, querying it causes an error.SearchResult = User | Post | Comment. You want to write a query that returns the name for User, title for Post, and content for Comment. Which query correctly fetches these fields?name on User, title on Post, and content on Comment correctly. Other options either query fields directly without fragments or use wrong fields.