Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

graphql
abstract types
data types

What are abstract types in GraphQL?

Mian Basam Ahmad

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
}
Union types

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
}
Interface type

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.

RELATED TAGS

graphql
abstract types
data types

CONTRIBUTOR

Mian Basam Ahmad
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring