What if you could handle many different data types as easily as one, without messy code?
Why Union types in GraphQL? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a list of different shapes like circles, squares, and triangles, and you want to store their details together. Without union types, you might try to create separate lists or force all shapes into one format, which gets messy fast.
Manually handling each shape type separately means writing lots of repetitive code and constantly checking which shape you are dealing with. This is slow, confusing, and easy to make mistakes, especially when adding new shapes.
Union types let you group different types under one umbrella cleanly. You can say, 'This can be a circle or a square or a triangle,' and GraphQL will handle the rest. This keeps your code simple and flexible.
type Circle { radius: Float }
type Square { side: Float }
type ShapeList { circles: [Circle], squares: [Square] }union Shape = Circle | Square
type ShapeList { shapes: [Shape] }Union types enable you to work with multiple related types seamlessly in one place, making your data queries simpler and more powerful.
Think of a social media app where a feed can show posts, photos, or videos. Using union types, the feed can return any of these content types without extra hassle.
Union types group different types under one name.
They reduce repetitive code and errors.
They make queries flexible and easier to manage.
Practice
union types in GraphQL?Solution
Step 1: Understand union type purpose
Union types allow a field to return one of several object types, grouping them logically.Step 2: Compare with other options
Defining a list of scalar values or creating a new scalar type describes scalars, not unions. Enforcing a single object type for a field contradicts the union concept.Final Answer:
To group multiple object types into one field that can return different types -> Option AQuick Check:
Union types = group multiple object types [OK]
- Confusing union with scalar types
- Thinking unions enforce a single type
- Mixing unions with interfaces
SearchResult that includes User and Post types?Solution
Step 1: Recall union syntax
Unions use the syntax:union Name = Type1 | Type2with pipe separators.Step 2: Check each option
union SearchResult = User | Post matches correct syntax. type SearchResult = User & Post uses & which is for intersections, not unions. interface SearchResult = User | Post wrongly uses interface keyword. union SearchResult { User, Post } uses braces which is invalid for unions.Final Answer:
union SearchResult = User | Post -> Option BQuick Check:
Union syntax uses '=' and '|' [OK]
- Using '&' instead of '|'
- Using braces {} instead of '='
- Confusing union with interface syntax
SearchResult = User | Post and this query:{ search { ... on User { name } ... on Post { title } } }What fields will be returned if the search result contains one User with name "Alice" and one Post with title "GraphQL Guide"?
Solution
Step 1: Understand inline fragments on union
The query uses inline fragments to selectnamefromUserandtitlefromPost.Step 2: Apply to data
Since the result has one User and one Post, the response includes both objects separately with their respective fields.Final Answer:
[{"name": "Alice"}, {"title": "GraphQL Guide"}] -> Option DQuick Check:
Inline fragments return fields per type separately [OK]
- Combining fields into one object
- Returning only one type's fields
- Ignoring inline fragment usage
union SearchResult = User | Post
And this query:
{ search { ... on User { id name } ... on Post { id title } } }Which of the following errors will occur if you try to query a field
email inside Post inline fragment like this:{ search { ... on User { id name } ... on Post { id title email } } }Solution
Step 1: Check Post type fields
Ifemailis not defined onPosttype, querying it causes an error.Step 2: Understand inline fragment validation
Inline fragments must only query fields existing on the specified type. Querying unknown fields causes errors.Final Answer:
Error: Field 'email' does not exist on type 'Post' -> Option CQuick Check:
Querying unknown fields on type causes error [OK]
- Assuming all fields exist on all union types
- Thinking unions disallow inline fragments
- Querying fields on wrong types
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?Solution
Step 1: Use inline fragments for each union type
Each type in the union requires its own inline fragment to query its specific fields.Step 2: Validate fields per type
{ search { ... on User { name } ... on Post { title } ... on Comment { content } } } queriesnameon User,titleon Post, andcontenton Comment correctly. Other options either query fields directly without fragments or use wrong fields.Final Answer:
{ search { ... on User { name } ... on Post { title } ... on Comment { content } } } -> Option AQuick Check:
Use inline fragments per type to query union fields [OK]
- Querying all fields directly without fragments
- Using wrong fields for a type
- Mixing fields inside fragments incorrectly
