HomeToolsAbout

Union and Intersection Types

What is it

Unions and Interfaces are abstract GraphQL types that enable a schema field to return one of multiple object types.

Union type

Field can have a union as its return type.

union Media = Book | Movie

You can return any object type that is included in the union:

type Query { allMedia: [Media] # media can be book or movie }

All union types must be object types.

  • They cannot be scalars or input types.

Included types do not need to share any fields.

Inline Fragments

If you are querying a field that returns an interface or a union type, you will need to use inline fragments to access data on the underlying concrete type.

query HeroForEpisode($ep: Episode!) { hero(episode: $ep) { name ... on Droid { primaryFunction } ... on Human { height } } }

In above example, hero field returns the type Characte which can be either a Human or Droid depending on the episode argument.

When asking for a field on the concrete type, you need to use inline fragments with a type condition.

  • If a Character returned from hero is of Droid type, ... on Droid fragment will be executed and primaryFunction field will be returned.
  • If a Chracter returned from hero is a Human type, ... on Human fragment will be executed and will return height field instead.

Querying a Union

Querying for __typename is almost always recommended, but it's even more important when querying a field that might return one of multiple types.

query GetSearchResults { search(contains: "Shakespeare") { __typename ... on Book { title } ... on Author { name } } }
AboutContact