Working with Union Types

1. Creating Union Types

ElementSyntax
Declarationunion Result = A | B | C
MembersObject types only (not interfaces, unions, scalars)
Common fieldsNone — must use ... on Type to select

Example: Search union

union SearchResult = User | Post | Product

type Query {
  search(q: String!): [SearchResult!]!
}

2. Defining Union Members

RuleDetail
Object onlyCannot include scalars, interfaces, unions, enums
Members differNo requirement they share fields
Min sizeAt least one member required

3. Querying Union Types

Example: Selecting from union

{
  search(q: "graphql") {
    __typename
    ... on User { id name }
    ... on Post { id title }
    ... on Product { id sku price }
  }
}
SelectionRequired?
__typenameRecommended for client discrimination
Inline fragmentRequired to access any field

4. Using Type Conditions

FormDetail
Inline... on User { ... }
Namedfragment UserFields on User { ... }
ValidationTarget must be a possible member of the union

5. Resolving Union Types

Example: __resolveType for union

const resolvers = {
  SearchResult: {
    __resolveType(obj) {
      if (obj.sku) return "Product";
      if (obj.title) return "Post";
      if (obj.email) return "User";
      return null;
    }
  }
};

6. Creating Search Result Unions

MemberDiscriminator
Useremail
Posttitle
Productsku
Taglabel

7. Creating Error Unions

Example: Result-or-error union

type LoginSuccess { token: String!, user: User! }
type InvalidCredentials { message: String! }
type AccountLocked { unlockAt: DateTime! }

union LoginResult = LoginSuccess | InvalidCredentials | AccountLocked

type Mutation { login(email: String!, password: String!): LoginResult! }

8. Combining Unions with Interfaces

PatternUse
Error interface + unionAll errors implement UserError; union returns success or any error type
Node + unionMembers all implement Node — clients can refetch by id

9. Narrowing Union Types

ToolDetail
__typenameSwitch on string in client code
TypeScript discriminated unionGenerated types make narrowing exhaustive
Apollo ClientConfigure possibleTypes for cache

10. Choosing Union vs Interface

Use UnionUse Interface
Members share NO fieldsMembers share fields
Result-or-error typesPolymorphic entities (Node, Comment owner)
Heterogeneous searchCommon pagination/sorting