Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท The Schema

Enums, Interfaces and Unions

Model fixed value sets with enums and shared or alternative shapes with interfaces and unions. Learn __typename and inline fragments with a runnable stand-in.

Object types and scalars get you far, but real domains have choices. An order has a status that is one of a few fixed values. A search box returns books and authors. A feed mixes photos, videos and text posts. GraphQL gives you three tools for that: enums for a closed set of values, interfaces for types that share fields, and unions for "one of these types" with nothing in common required.

The SDL snippets and queries below are read-only; no server runs on this site. The runnable example is a stand-in that resolves a value to a concrete type and applies inline fragments, which is what a real execution engine does for every interface or union field.

Enums

An enum is a scalar that can only be one of a named set of values.

GRAPHQL
enum OrderStatus {
  PENDING
  SHIPPED
  DELIVERED
  CANCELLED
}

type Order {
  id: ID!
  status: OrderStatus!
}

type Query {
  orders(status: OrderStatus): [Order!]!
}

In a query you write the value without quotes: orders(status: SHIPPED). The response contains the name as a JSON string: "status": "SHIPPED". Passing "SHIPPED" in quotes inside the document is a validation error, but a variable of type OrderStatus is sent as the JSON string "SHIPPED".

Enums beat free strings because the schema documents the allowed values, tools auto-complete them, and invalid input is rejected before any resolver runs. Use SCREAMING_SNAKE_CASE by convention. Adding a value later can break clients that switch over all values, so decide whether clients must handle unknown values (usually yes, with a default branch).

Interfaces

An interface is a list of fields that several object types promise to provide.

GRAPHQL
interface Node {
  id: ID!
}

interface Media {
  id: ID!
  title: String!
}

type Photo implements Media & Node {
  id: ID!
  title: String!
  width: Int!
  height: Int!
}

type Video implements Media & Node {
  id: ID!
  title: String!
  seconds: Int!
}

type Query {
  media: [Media!]!
}

Every type that implements an interface must repeat all of its fields with compatible types, and may add more. A field returning Media can hold a Photo or a Video, so a client can always ask for id and title:

GRAPHQL
{
  media {
    id
    title
  }
}

To reach fields that belong to only one implementing type, use an inline fragment with a type condition (you met fragments in Aliases and Fragments):

GRAPHQL
{
  media {
    __typename
    id
    title
    ... on Photo {
      width
      height
    }
    ... on Video {
      seconds
    }
  }
}

__typename

__typename is a meta-field available on every object, interface and union selection. It returns the name of the concrete object type of the value. Clients use it to know which shape arrived, and caches such as Apollo use it, together with id, to build cache keys (Clients, Apollo and Code Generation). With interfaces and unions, add it whenever you use fragments.

Unions

A union says "this field is exactly one of these object types", without requiring shared fields.

GRAPHQL
union SearchResult = Book | Author | Publisher

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

Because a union has no fields of its own, you can only select __typename directly; everything else needs an inline fragment:

GRAPHQL
{
  search(text: "ada") {
    __typename
    ... on Book { title }
    ... on Author { name }
    ... on Publisher { name country }
  }
}

A union can only contain object types, not scalars, interfaces, or other unions.

Which one do I need?

Enum A closed set of named values.
Interface Types that share fields.
Union One of several unrelated types.

Enum is a value; interface and union are shapes.

1 / 2

Interface or union?

  • Pick an interface when the types genuinely share fields and clients want to use those fields without fragments (id, title, createdAt). It also lets you add a shared field in one place.
  • Pick a union when the alternatives have little in common, or when you model results such as CreatePostResult = Post | ValidationError (see Modeling Errors).
  • An object type can implement several interfaces, but a field has only one declared type, so a union is the tool for mixing unrelated types in one list.

How the server decides: type resolution

For an interface or union, the executor needs to know which object type a value is, so it can pick the right fields and fragments. Servers ask the schema for a type-resolver, often called resolveType or __resolveType, which returns a type name. A very common implementation looks at a field on the underlying data.

Here is a stand-in with that logic and a tiny inline-fragment evaluator. The "query" is data, not text: a list of plain fields plus a map from type conditions to extra fields. It is not a GraphQL parser or validator.

JS Stand-in: resolve a type, apply inline fragments

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the Photo rows get width and height, the Video row gets seconds, and nothing is added for a fragment whose type does not match. That is the behaviour of ... on Photo { ... } on a value that turns out to be a Video: the fragment is skipped, not an error. The last lines show why enums are safe: "shipped" in lower case is simply not in the set, and a real server rejects it during validation.

A union stand-in

Unions work the same way, except there are no shared fields to fall back on. This stand-in resolves each search hit by the shape of its data, then groups the hits by __typename, as a client would after receiving the response.

JS Stand-in: a SearchResult union

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both Author and Publisher have a name, but each fragment still names its own type: the fields are looked up per member, never "on the union".

Common mistakes

  • Forgetting __typename. Without it, a client getting a mixed list cannot tell a Photo from a Video unless fields happen to differ.
  • Using an interface to share only a name. If the types have nothing meaningful in common, a union communicates the design better.
  • Returning a value whose type resolver fails. The error is a field error, so it follows the null rules from Lists and Non-Null Types.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you write an enum value in a query?

    Enum values in a GraphQL document are bare names. A variable of an enum type is sent as a JSON string.
  2. 2. What must an object type do to implement an interface?

    It must provide every interface field and may add more of its own.
  3. 3. Which fields can you select directly on a union-typed field?

    A union has no fields of its own, so only __typename is allowed outside an inline fragment.
  4. 4. Why is __typename important with fragments?

    The client uses it to decide how to read and render each item, and caches use it in cache keys.
  5. 5. Which is the best fit for CreatePostResult = Post | ValidationError?

    The two members share nothing, and the field returns exactly one of them, which is what a union models.

Summary

  • An enum is a closed set of named values, written without quotes in queries and validated before resolvers run.
  • An interface declares shared fields; implementing types must provide them and can add more.
  • A union is "one of these object types"; its members need not share fields.
  • Use inline fragments (... on Type) to reach type-specific fields, and select __typename to learn the concrete type.
  • The server needs a type resolver to decide which object type a value is.
  • Choose an interface for shared fields, a union for unrelated alternatives such as result types.

Next: Input Types, Custom Scalars and Introspection.