GraphQL Interface Polymorphism Pattern
Model polymorphic types with GraphQL interfaces to share field contracts across different object types while keeping resolvers type-specific.
Overview
GraphQL interfaces define a contract shared by several object types. An interface declares a set of fields that every adopting type must include, and each object type adds its own fields on top. Clients query the shared fields without knowing the concrete type, and reach type-specific fields through inline fragments.
Interfaces are GraphQL’s equivalent of abstract classes in object-oriented languages. They model polymorphic relationships, like a search result that could be a Post, a Comment, or a User, while keeping the schema strongly typed. The GraphQL spec section on interfaces defines the contract: an object type that declares implements must include every interface field with a compatible type, or schema validation fails before the server starts.
The pattern matters because polymorphism shows up constantly in real APIs: feeds, notifications, search results, activity logs. Without interfaces you’d either return a bloated single type full of nullable fields, or force clients to query each concrete type separately.
When to Use
- A field can return several types that share a common subset of fields (search results, notifications, feed items)
- You need a common contract across types but each type still has its own fields
- Modeling real hierarchies where “is a” holds (a Post is a Node; a Dog is an Animal)
- Relay-style global object identification, where every fetchable type adopts
Node { id: ID! }
When Not to Use
- The types share no fields at all. A
unionexpresses that better, since unions require no shared contract - Only one concrete type declares the interface today and none is expected. The abstraction buys nothing
- The interface would end up with zero fields, which is just an empty contract
- You’re modeling an either/or result like success vs error. The error extension pattern or a result union is a better fit
Solution
The running example: a content platform where Query.feed returns posts, comments, and users, and Query.search returns anything searchable.
1. Define the Interfaces
interface Node {
id: ID!
createdAt: String!
updatedAt: String!
}
interface Searchable {
id: ID!
title: String!
snippet: String!
searchScore: Float!
}
Two small interfaces beat one fat one. Node is about identity and timestamps; Searchable is about being returned by search. A type picks up exactly the contracts it needs.
2. Implement the Interfaces in Object Types
type Post implements Node & Searchable {
id: ID!
createdAt: String!
updatedAt: String!
title: String!
snippet: String!
searchScore: Float!
# Post-specific fields
body: String!
tags: [String!]!
author: User!
}
type Comment implements Node {
id: ID!
createdAt: String!
updatedAt: String!
# Comment-specific fields
body: String!
author: User!
post: Post!
}
type User implements Node {
id: ID!
createdAt: String!
updatedAt: String!
# User-specific fields
name: String!
email: String!
posts: [Post!]!
}
Every field declared in the interface must be re-declared on the implementing type; GraphQL doesn’t auto-inject them. Field types can be narrowed covariantly: if the interface declares author: Person, the object may declare author: User as long as User is itself a Person.
3. Resolve the Concrete Type
When a field returns an interface, GraphQL must learn which object type each returned object actually is. That mapping happens in __resolveType, a resolver the schema calls once per abstract-typed object in the response. Per the Apollo Server docs on unions and interfaces, it must return the GraphQL type name as a string.
The reliable way is a discriminator: each object carries the answer with it. Rows loaded from a posts table are posts; give them a __typename or a kind column at the data layer and resolution becomes a lookup, not a guess:
const resolvers = {
Node: {
__resolveType: (obj) => obj.__typename ?? null,
},
Searchable: {
__resolveType: (obj) => obj.__typename ?? null,
},
Post: {
author: (post, _args, { loaders }) => loaders.userLoader.load(post.authorId),
tags: (post) => post.tags ?? [],
},
Comment: {
author: (comment, _args, { loaders }) => loaders.userLoader.load(comment.authorId),
post: (comment, _args, { db }) => db.post.findById(comment.postId),
},
User: {
posts: (user, _args, { db }) => db.post.findMany({ where: { authorId: user.id } }),
},
};
If every data source already tags objects with __typename (Apollo Server’s default resolveType checks this property automatically), you can omit __resolveType entirely. Keep it explicit anyway when objects come from a shared table, say a feed_items table where a kind column decides the type, and map kind to the GraphQL type name in one place:
const KIND_TO_TYPE = { post: 'Post', comment: 'Comment', user: 'User' };
const resolvers = {
Node: {
__resolveType: (obj) => KIND_TO_TYPE[obj.kind] ?? null,
},
};
4. Querying Interface Fields
Clients query shared fields directly and reach type-specific fields with inline fragments:
query {
search(term: "graphql") {
# Shared fields from the Searchable interface
id
title
snippet
searchScore
# Type-specific fields via inline fragments
... on Post {
body
tags
author {
name
}
}
... on Article {
url
wordCount
}
}
}
The response includes __typename on each item, so client code can render per type even before the fragments resolve. Inline fragments are also the only way to apply a fragment condition: ... on Post skips its fields entirely for items that aren’t posts.
5. Interface Fields in Lists and Root Fields
type Query {
feed: [Node!]! # A mix of Post, Comment, and User objects
search(term: String!): [Searchable!]!
node(id: ID!): Node # Relay-style global node lookup
}
const resolvers = {
Query: {
feed: (_parent, _args, { db }) => db.feed.getRecent(),
search: (_parent, { term }, { db }) => db.search.search(term),
node: (_parent, { id }, { db }) => db.node.findById(id),
},
};
Nothing stops a single resolver from returning a list that mixes concrete types. __resolveType then runs once per item, which is why it must stay cheap (see Common Mistakes).
6. Relay-Style Global ID Resolution
The Relay Global Object Identification spec formalizes Node as the lookup contract: every fetchable object gets a globally unique id, and Query.node(id) returns it. A common encoding packs the type name into the id itself:
function globalIdToType(id: string): { type: string; id: string } {
const [type, localId] = Buffer.from(id, 'base64').toString().split(':');
return { type, id: localId };
}
const resolvers = {
Query: {
node: async (_parent, { id }, { db }) => {
const { type, id: localId } = globalIdToType(id);
switch (type) {
case 'Post': return { __typename: 'Post', ...(await db.post.findById(localId)) };
case 'User': return { __typename: 'User', ...(await db.user.findById(localId)) };
case 'Comment': return { __typename: 'Comment', ...(await db.comment.findById(localId)) };
default: throw new Error(`Unknown node type: ${type}`);
}
},
},
Node: {
__resolveType: (obj) => obj.__typename ?? null,
},
};
Note how the resolver attaches __typename at the boundary, so __resolveType stays a pure lookup even though the underlying rows come from three different tables.
Explanation
How the pieces fit together:
- Interface contract: every implementing type re-declares all interface fields. The schema validator checks this at startup, so a missing field fails fast instead of surfacing as a runtime null.
__resolveType: GraphQL invokes it once for every object sitting under an abstract return type, and whatever it returns drives fragment matching:... on Postfields only execute when the resolved type isPost(or a subtype of it).- Interface field resolvers: a resolver defined on the interface applies to every implementing type unless that type overrides it. Useful for computed shared fields, and easy to misuse if the implementation depends on fields only some types have.
- Covariant narrowing: an implementing type may declare a field with a more specific type than the interface’s, as long as the narrower type is a subtype.
Searchable.snippet: String!can becomePost.snippet: String!or stay identical; what you can’t do is widen it or change nullability against the contract. - Interfaces vs unions: interfaces require shared fields and let clients query them unfragmented; unions (
union Result = Post | User | Comment) require nothing shared and force every field access through fragments. When every union member happens to share fields anyway, switching to an interface gives clients a better experience.
| Interface | Union | |
|---|---|---|
| Shared fields required | Yes, all members re-declare them | None |
| Query shared fields without fragments | Yes | No |
implements in SDL | Yes | Members listed on the union itself |
| Best for | Types with a real common contract | Either/or results, disjoint types |
| Example | Node, Searchable, Character | SearchResult = Post | Video | Ad |
Both are abstract types resolved by __resolveType, so the discriminator advice above applies to unions too.
Variants
Multiple Interface Implementation
A type can implement as many interfaces as it needs:
interface Timestamped {
createdAt: String!
updatedAt: String!
}
interface Ownable {
owner: User!
}
type Document implements Node & Timestamped & Ownable {
id: ID!
createdAt: String!
updatedAt: String!
owner: User!
title: String!
content: String!
}
Document answers to Node, Timestamped, and Ownable fields, so it can appear in a feed ([Node!]!), an audit query ([Timestamped!]!), and a per-owner listing.
Interface with Default Field Resolver
const resolvers = {
Timestamped: {
// Applies to every implementing type unless overridden
createdAt: (obj) => obj.createdAt,
updatedAt: (obj) => obj.updatedAt,
ageInDays: (obj) => {
const diff = Date.now() - new Date(obj.createdAt).getTime();
return Math.floor(diff / (1000 * 60 * 60 * 24));
},
},
};
Post inherits createdAt, updatedAt, and ageInDays without declaring resolvers of its own.
Interface Inheriting from Another Interface
Interfaces can inherit from other interfaces (supported since GraphQL-js 16 / the October 2021 spec):
interface Entity {
id: ID!
}
interface TimestampedEntity implements Entity {
id: ID!
createdAt: String!
}
type Article implements TimestampedEntity & Entity {
id: ID!
createdAt: String!
title: String!
}
The transitive chain matters: Article must declare both id and createdAt, and it can be returned anywhere an Entity is expected.
Union with Shared Interface Fields
interface SearchResult {
id: ID!
title: String!
}
type PostResult implements SearchResult {
id: ID!
title: String!
body: String!
}
type VideoResult implements SearchResult {
id: ID!
title: String!
duration: Int!
}
union SearchItem = PostResult | VideoResult
type Query {
search(term: String!): [SearchItem!]!
}
Clients still query through inline fragments on the union, but every member honors the SearchResult contract. This is the escape hatch when members share fields but you also want member types that can’t guarantee the contract forever: the union caps the membership list explicitly.
Best Practices
- Keep interfaces focused on one concern (
Nodefor identity,Timestampedfor audit fields,Ownablefor ownership) instead of one fat contract - Resolve
__resolveTypefrom a discriminator the data layer already stores (__typename, akindcolumn, the table the row came from). Never infer the type from which fields happen to be non-null - Keep
__resolveTypesynchronous and cheap. It runs once per abstract object; a database lookup inside it multiplies the cost of every list - Document which types satisfy each interface using schema descriptions; clients planning fragments need that list, and tooling surfaces it
- Use the
Nodeinterface for anything fetchable by global id; Relay clients assume it - Prefer interfaces over unions when members share fields: unfragmented shared-field access is a meaningfully better client DX
- For a deeper guide, see the Complete Guide to GraphQL Schema Design
Common Mistakes
- Guessing the type from data shape:
if (obj.body && obj.tags) return 'Post'silently breaks the day a Comment gains tags or a Post arrives without them. Store the type explicitly - Missing
__resolveType: without it (or__typenameon objects) GraphQL can’t pick a concrete type and returns “Abstract type X must resolve to an Object type” for every item - Returning a wrong or misspelled type name:
__resolveTypemust return a string matching a type in the schema, and the object’s class name or constructor name may not match - Declaring
implementswithout the fields: schema validation catches this at startup, but it still bites when fields get removed from the object type during refactors - Slow
__resolveType: a resolver that queries the database to figure out the type turns every 50-item feed into 50 extra queries. If you’re already loading objects per item, the DataLoader pattern covers batching, but the fix here is a stored discriminator, not a faster lookup - Union where an interface belongs: clients end up writing
... on Post { id } ... on User { id }for fields every member has
See Also
Frequently Asked Questions
What is the difference between an interface and a union in GraphQL?
An interface declares shared fields that every implementing type must include; clients can query those fields without fragments. A union skips the shared-field requirement entirely, and on the client side that means every field access has to go through an inline fragment. Reach for interfaces when members share a contract, unions when they don't. The either/or result of a mutation (CreatePostResult = Post | ValidationError) is the classic union case.
Can a GraphQL type implement multiple interfaces?
Yes: type Post implements Node & Searchable & Ownable. The type must declare every field from every interface, and it can be returned anywhere any of those interfaces is expected.
How does __resolveType work?
GraphQL calls __resolveType once for each object returned under an abstract type (interface or union). It receives the resolved object and must return the concrete type name as a string. If it returns null or an unknown name, that list item errors out. Objects that carry __typename may not need it at all, since graphql-js and Apollo Server check that property by default.
Should I use the Node interface for global identification?
Yes, if you want Relay compatibility or consistent node(id) lookups. The Relay spec fixes the contract: id: ID! globally unique, Query.node(id: ID!): Node. Every type that can be looked up by a global id is a Node.
Can interfaces implement other interfaces?
Yes. Since the October 2021 spec (graphql-js 16), interface TimestampedEntity implements Entity is valid, and object types implementing TimestampedEntity must satisfy the whole chain. Before that version the keyword combination was a schema error.
Does __resolveType run for every object or every field?
Once per abstract-typed object in the response, not per field. Run a feed of 100 nodes and __resolveType fires 100 times, no matter how few fragments the query carries. It can never afford a database round-trip.
Related Resources
GraphQL Schema Stitching Pattern
Merge multiple independent GraphQL schemas into a single unified schema that clients can query as one graph.
PatternGraphQL Error Extension Pattern
Attach structured metadata to GraphQL errors using extension codes for predictable client-side error handling.
GuideComplete Guide to GraphQL Federation
Build and operate unified GraphQL APIs across multiple services with Apollo Federation. Covers subgraphs, supergraph composition, entity resolution, router deployment, security, and observability.
PatternGraphQL DataLoader Pattern
The DataLoader library pattern: batch individual load() calls into one request, dedupe keys per tick, and cache results per request. Contract, options, and pitfalls.
GuideComplete Guide to GraphQL Schema Design
Design GraphQL schemas that evolve without breaking clients. Type design, connections, mutations, error handling, and schema-first vs code-first.
GuideComplete Guide to GraphQL Security
Secure a production GraphQL API: introspection control, depth and cost limits, rate limiting, persisted queries, injection prevention, and error sanitization.