Unions
and Interfaces
are abstract GraphQL types that enable a schema field to return one of multiple object types.
Union
typeField 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.
scalars
or input
types.Included types do not need to share any fields.
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
.
Character
returned from hero
is of Droid
type, ... on Droid
fragment will be executed and primaryFunction
field will be returned.Chracter
returned from hero
is a Human
type, ... on Human
fragment will be executed and will return height
field instead.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 } } }