Q17: What are GraphQL Union types and how do they differ from Interfaces?
A union type represents a object choice across multiple concrete types, but members do not need to share common fields (unlike an interface).
Union Definition and Querying
union SearchResult = User | Post | Comment
query Search {
search(text: "graphql") {
... on User {
name
}
... on Post {
title
}
}
}💡 Inline fragments (
... on Type) query specific fields from union options.Key Takeaways
- Unions group distinct types without enforcing common fields.
- Inline fragments must be used to select fields from union options.
Knowledge Check
How do clients query distinct fields on a Union return type?