What are abstract types in GraphQL?

GraphQL abstract types

In order to provide an easy-to-use, versatile API to our users, we need to understand how to leverage abstract types of modeling in addition to concrete forms.

Unions and interfaces are GraphQL abstract types that allow a schema field to return one of several object types.

Union types

A union type in GraphQL is a polymorphic type. This means that it allows many kinds to be grouped together in a single field. Consider the following schema:

type Coordinates {
x: Int
y: Int
z: Int
}
type Dimensions {
dimensionsType: Coordinates
description: String
}
union SearchResult = Coordinates | Dimensions
type Query {
search(pattern: String): SearchResult
}

In this code, SearchResult is the union type. Various types can be modeled with the help of search results.

Interface types

Interfaces allow us to define a collection of fields that we may use to make sure that all objects in our schema have fields provided in the interface. At runtime, interfaces also serve as a sort of polymorphism. We can make the type of a field an interface, which allows us to return any type that implements the interface.

interface NDimension{
url: String
}
type Coordinate implements NDimension {
X: Int
Y: Int
}
type Query {
search(pattern: String): NDimension
}

When a client submits a search query, the interface allows them to choose common fields. This is in contrast to unions, in which GraphQL assumes that there is no overlap between members. Interfaces, on the other hand, represent the intersection of fields between implementors and can thus be picked without qualification.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved