Check out a free preview of the full Introduction to GraphQL course:
The "Unions" Lesson is part of the full, Introduction to GraphQL course featured in this preview video. Here's what you'd learn in this lesson:

Scott explains how to utilize unions, which allow the user to return more than just one type.

Get Unlimited Access Now

Transcript from the "Unions" Lesson

[00:00:00]
>> Scott Moss: Unions, they're very much like interfaces, but the difference is is that they're a combination type that can be one of many different types. They may not relate to each other. So what does that actually mean? Basically it's sometimes you want a query to return a possibility of more than just one type.

[00:00:18] Unions allow you to create that type that's composed of many types. It's like a OR. It's like this type, or this type, or this type, or this type, or this type, and they can have no relationship to each other, absolutely none. The one good example I can think of is searches.

[00:00:32] So if you're using GraphQL to do searching, like, yeah, I wanna implement search in my website, I wanna search for all this stuff. But you can search for images, you can search for users, you can search for locations, you can search for restaurants, all these different types of things.

[00:00:45] A union is great for that because each one of those will be a GraphQL type, and you want your search query result to return either one of those. So that's where it's really great. The only difference, as far as implementation goes, for you on the server, when it comes to unions, is one word.

[00:01:02] It's instead of doing an interface like this and implementing it for a union, all you would do is you would just get all the types that you want. For instance, I'm just gonna make up some types here.
>> Scott Moss: We'll say, union, we'll do the Animal. Well, let's just say union SearchItem.

[00:01:26] And then that's gonna equal, then you start putting the types that you want. So if I had a person, I could say Person. Then I could say Place, then I could say a Review, whatever I wanted to search for, a Restaurant, you get the point. So that's how you would create a union.

[00:01:47] And then this is gonna create a union type that you can use the exact same way you can use a interface. So the same way you use an interface, you're now able to use a union. And the way that that's resolved on the client, it's the same thing as this.

[00:02:01] They still have to use inline fragments to resolve that. They still have to do it. So it doesn't really change anything for you, all you do is just do this now. You still have to write a resolveType for that union to resolve which type is being resolved. You still have to do that.

[00:02:17] And that's it, nothing else changes for you. So I almost never use unions cuz I don't even do search with GraphQL, but interfaces I use a lot. But yeah, that's the only difference.