What if you could handle many different data types as easily as one, without messy code?
Why Union types in GraphQL? - Purpose & Use Cases
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.