⬡ GraphQL Beginner

What are union types in GraphQL?

Answer

Union types define a field that can return one of several different object types, without requiring shared fields. Definition: union SearchResult = User | Post | Comment. Usage: type Query { search(term: String!): [SearchResult!]! }. Unlike interfaces, union members don't share any fields — you must use inline fragments for all fields: { search(term: "Alice") { ... on User { name } ... on Post { title } ... on Comment { text } } }. The server must define a __resolveType function to determine which concrete type to return. Use __typename to identify the type at runtime. Unions are ideal for: search results, notification feeds, event logs, or any field that can legitimately return different object types. Interfaces are preferred when types share common fields.