Patternite Logo

Multiple field types in GraphQL

1

We can use the `union` type to ensure a field can return differing object types

Loading...

Schema

Often times we will want to have multiple object types for a GraphQL field. In the above example, when we query a user by their username field, we would like to return either the user's id, or the actual User object. We can do this by defining a union type on line #2 called UserOrId. Fields with this type can either return a User object, or a UserId object. Note that, since GraphQL does not allow unions with scalar types (such as ID), we must define a custom UserId object. In general, we could chain any number of types together (i.e. Type1 | Type2 | Type3 | ...) as needed.

Query

To query a union field, we use the ... on Type syntax as in lines #22 and #25, to determine what data we want depending on the object type that is returned. The __typename field is optional, but tells the client what type was returned by the query.

The official GraphQL docs and the Apollo docs have good overviews of union types.

Profile picture for duncster

| edited

Patternite © 2021

Patternite Logo