Inline Fragments and Polymorphic Results

Interfaces and unions create polymorphic results. A single field may return different concrete object types, and clients need a way to request fields specific to each type.

Consider:

union SearchResult = User | Product

A query can use inline fragments:

query Search {
  search(term: "phone") {
    ... on User {
      id
      name
    }
    ... on Product {
      id
      name
      price
    }
  }
}

The ... on User fragment applies only when the runtime object is a User. The ... on Product fragment applies only when it is a Product.

This allows a client to work with a heterogeneous result set while preserving the type safety of the schema.

GraphQL also exposes the __typename meta-field:

search(term: "phone") {
  __typename
}

The response might contain:

{
  "__typename": "Product"
}

__typename is particularly useful when clients need to determine the concrete runtime type or when normalized caching systems need a type name.

Querying a Union
query Search($term: String!) {
  search(term: $term) {
    __typename
    ... on User {
      id
      name
    }
    ... on Product {
      id
      name
      price
    }
  }
}

The result can contain either User or Product. __typename identifies the concrete runtime type. Each inline fragment requests fields that are valid for its corresponding type.

Key Takeaways
  • Inline fragments select fields based on runtime type.

  • They are essential when working with interfaces and unions.

  • __typename identifies the concrete GraphQL runtime type.

  • Polymorphic schemas can model heterogeneous results safely.

Knowledge Check

What does __typename provide in a GraphQL response?