Polymorphic results
A field may return several concrete object types that share fields such as an identifier and display name.
GraphQL · Const
A GraphQL interface is an abstract type that declares shared fields for object or interface implementations. It lets one field return different concrete types through a common contract.
An interface is an abstract GraphQL type containing fields that implementing object or interface types must also provide. It is useful when one field may return concrete objects of different types while exposing their shared fields; clients use inline fragments for type-specific fields.
interface Character {
id: ID!
name: String!
}A field declared with an interface return type yields a concrete object type that implements that interface.
interface Character {
id: ID!
name: String!
}
type Human implements Character {
id: ID!
name: String!
homePlanet: String
}
type Droid implements Character {
id: ID!
name: String!
primaryFunction: String
}
type Query {
characters: [Character!]!
}This schema defines shared fields on Character and lets Human and Droid provide concrete implementations. A field returning Character can therefore produce either object type.
A field may return several concrete object types that share fields such as an identifier and display name.
A schema needs a common contract for multiple domain entities while retaining implementation-specific fields.
Clients need predictable common selections plus optional fields for each concrete result type.
An interface is an abstract type that declares shared fields. Object types or other interfaces implement it and must include those fields, so a field can return different concrete object types through one common contract.
Follow-up: How do clients request implementation-specific fields? They use inline fragments, such as ... on Human, and can request __typename to identify the concrete object type.
An implementing type must contain the interface's fields with the same arguments and return types. This preserves a predictable shared selection set across all possible returned object types.
Follow-up: What happens when a field returns an interface? Execution returns a valid implementing object type, and the client can use fragments for fields not declared by the interface.
Interfaces are useful when a field may return objects of several types that share common data. For example, Character can expose id and name while Human and Droid add different fields.
Follow-up: How can a query access those added fields? Use inline fragments targeted at each possible concrete type, while selecting shared fields directly on the interface.
Object typesUnion typesInline fragments__typenameSchemas and Types