TExcelTAD
Home › GraphQL › Unions

Unions

A union type says "this field returns one of these object types", without requiring any shared fields. It's the natural fit for a search box that finds users, repositories and issues, or for a feed that mixes photos and text posts.

Declaring a union

graphql
union SearchResult = User | Repository | Issue

Members must be object types (not scalars, interfaces or other unions). Since a union guarantees no common fields, you can only select __typename directly; everything else goes into inline fragments.

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type User { login: String!, followers: Int! }
  type Repository { name: String!, stars: Int! }
  type Issue { number: Int!, title: String! }

  union SearchResult = User | Repository | Issue

  type Query { search(text: String!): [SearchResult!]! }
`);

const everything = [
  { __typename: 'User', login: 'graphdev', followers: 1200 },
  { __typename: 'Repository', name: 'graph-tools', stars: 860 },
  { __typename: 'Issue', number: 42, title: 'graph view is slow' },
  { __typename: 'Repository', name: 'paint', stars: 75 },
];

const rootValue = {
  search: ({ text }) =>
    everything.filter((item) => JSON.stringify(item).includes(text)),
};

const query = `{
  search(text: "graph") {
    __typename
    ... on User { login followers }
    ... on Repository { name stars }
    ... on Issue { number title }
  }
}`;

const result = await graphql({ schema, source: query, rootValue });
for (const item of result.data.search) console.log(JSON.stringify(item));
{"__typename":"User","login":"graphdev","followers":1200}
{"__typename":"Repository","name":"graph-tools","stars":860}
{"__typename":"Issue","number":42,"title":"graph view is slow"}

The client always asks for __typename so it knows how to render each item.

Only __typename is shared

Even if all members happen to have a field with the same name, you can't select it on the union directly:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Photo { url: String!, caption: String }
  type Note { text: String!, caption: String }
  union Post = Photo | Note
  type Query { feed: [Post!]! }
`);

const result = await graphql({ schema, source: '{ feed { caption } }', rootValue: { feed: [] } });
console.log(result.errors[0].message);
Cannot query field "caption" on type "Post". Did you mean to use an inline fragment on "Note" or "Photo"?

If you want shared fields, that's an interface's job. You can also use both: union members may implement interfaces, and ... on SomeInterface { … } works inside a union selection.

Unions for results and errors

A popular design uses unions to return expected errors as data instead of top-level errors. The schema then documents every outcome, and clients are forced to handle them:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Coupon { code: String!, percentOff: Int! }
  type CouponNotFound { code: String! }
  type CouponExpired { code: String!, expiredOn: String! }

  union RedeemResult = Coupon | CouponNotFound | CouponExpired

  type Query { _unused: Int }
  type Mutation { redeem(code: String!): RedeemResult! }
`);

const coupons = {
  SPRING10: { percentOff: 10, expiresOn: '2027-04-30' },
  WINTER25: { percentOff: 25, expiresOn: '2026-02-28' },
};
const today = '2026-06-01';

const rootValue = {
  redeem: ({ code }) => {
    const coupon = coupons[code];
    if (!coupon) return { __typename: 'CouponNotFound', code };
    if (coupon.expiresOn < today) return { __typename: 'CouponExpired', code, expiredOn: coupon.expiresOn };
    return { __typename: 'Coupon', code, percentOff: coupon.percentOff };
  },
};

const mutation = `mutation Redeem($code: String!) {
  redeem(code: $code) {
    __typename
    ... on Coupon { percentOff }
    ... on CouponExpired { expiredOn }
  }
}`;

for (const code of ['SPRING10', 'WINTER25', 'FREE99']) {
  const result = await graphql({ schema, source: mutation, rootValue, variableValues: { code } });
  console.log(code.padEnd(9), JSON.stringify(result.data.redeem));
}
SPRING10  {"__typename":"Coupon","percentOff":10}
WINTER25  {"__typename":"CouponExpired","expiredOn":"2026-02-28"}
FREE99    {"__typename":"CouponNotFound"}

CouponNotFound came back with only __typename, because the query selected no fields for it. That's fine: the type name alone tells the client what happened.

Resolving the member type

As with interfaces, the engine needs to know each object's concrete type. Options in graphql-js:

Approach How
__typename property in the data works out of the box (used above)
resolveType(value) on the union return the type name, e.g. based on a field
isTypeOf(value) on each object type each member checks whether a value belongs to it

If none of them gives an answer, the field fails with an "Abstract type … must resolve to an Object type at runtime" error.

Test yourself

Which field can you select directly on a union, without a fragment?

  1. Any field all members share
  2. id
  3. __typename
  4. None at all

Which of these can be a member of a union?

  1. String
  2. An object type
  3. An interface
  4. Another union

Why return a CouponExpired type instead of throwing an error?

  1. Errors are not allowed in mutations
  2. It makes expected outcomes part of the schema that clients can query
  3. It is faster
  4. Unions can't contain errors