Inline Fragments and Type Conditions
You'll learn how to query fields on union types and interfaces by using inline fragments with type conditions.
What's the Problem?
When you query a GraphQL field that returns an interface or union type, the server could send back one of several possible object types. Each type might have unique fields that don't exist on the others. How do you tell GraphQL which fields to fetch for which type?
Inline Fragments to the Rescue
An inline fragment lets you conditionally select fields based on the actual type returned. You use the ... on TypeName syntax to specify "if this result is a TypeName, then fetch these fields."
Think of it like a type-specific filter: you're saying "I know this could be different things—here's what to grab for each possibility."
query SearchResults {
search(term: "Apollo") {
... on Book {
title
author
isbn
}
... on Article {
title
publishedDate
magazine
}
... on Video {
title
duration
url
}
}
}
Here, search might return a union of Book | Article | Video. The inline fragments (... on Book, ... on Article, etc.) tell GraphQL: "When you encounter a Book, fetch isbn; when you encounter a Video, fetch duration"—and so on.
When to Use Them
- Union types: Multiple unrelated types in one result
- Interfaces: Querying specific fields on implementations
- Polymorphic lists: Arrays containing mixed types
You can combine inline fragments with regular fragments you've already defined, giving you full flexibility over complex, type-varied queries.
Key Takeaway: Inline fragments with type conditions (... on TypeName) let you query type-specific fields when a GraphQL field returns an interface or union, ensuring you fetch exactly what each type offers.