0
0
GraphQLquery~3 mins

Why Union types in GraphQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could handle many different data types as easily as one, without messy code?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
type Circle { radius: Float }
type Square { side: Float }
type ShapeList { circles: [Circle], squares: [Square] }
After
union Shape = Circle | Square
type ShapeList { shapes: [Shape] }
What It Enables

Union types enable you to work with multiple related types seamlessly in one place, making your data queries simpler and more powerful.

Real Life Example

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.

Key Takeaways

Union types group different types under one name.

They reduce repetitive code and errors.

They make queries flexible and easier to manage.