Skip to main content

Working with Interfaces

1. Creating Interface Types

ElementSyntax
Declarationinterface Name { fields }
Required fieldAll implementers must provide it
ArgsImplementer must accept same args (may add nullable extras)

Example: Interface

interface Node { id: ID! }
interface Timestamped {
  createdAt: DateTime!
  updatedAt: DateTime!
}

2. Implementing Interfaces

Example: Multiple interfaces

type Post implements Node & Timestamped {
  id: ID!
  createdAt: DateTime!
  updatedAt: DateTime!
  title: String!
}
RuleDetail
Field setSuperset of interface fields
CovarianceReturn type may be subtype (Node → User)
MultipleSeparated by &

3. Defining Common Fields

Common PatternFields
Nodeid: ID!
TimestampedcreatedAt, updatedAt
Soft-deletabledeletedAt: DateTime
Ownedowner: User!

4. Querying Interface Fields

Example: Interface field selection

query {
  node(id: "123") {
    id
    __typename
    ... on User { email }
    ... on Post { title }
  }
}
SelectionAllowed
Interface fieldsDirect selection
Concrete fieldsInline fragment ... on Type
__typenameAlways allowed for type discrimination

5. Resolving Abstract Types

Example: __resolveType

const resolvers = {
  Node: {
    __resolveType(obj) {
      if (obj.email) return "User";
      if (obj.title) return "Post";
      return null;
    }
  }
};
ApproachDetail
__resolveTypeReturns concrete type name string
isTypeOf (per type)Predicate function on each type
Discriminator fieldUse a stored __type column

6. Interface Implementing Interface

Example: Hierarchical interfaces

interface Node { id: ID! }
interface Resource implements Node {
  id: ID!
  url: String!
}
type Image implements Resource & Node {
  id: ID!
  url: String!
  width: Int!
}
RuleDetail
InheritanceInterface lists parent interface in implements
TransitiveImplementing types must list every interface in the chain

7. Using Type Conditions

FormUse
Inline fragment... on User { email }
Named fragmentfragment U on User { email }
ValidityType must be possible value of parent abstract type

8. Creating Polymorphic Schemas

PatternExample
Notificationsinterface Notification { id, createdAt }
Activity FeedCommon actor, varying object
Search resultsUnion or interface across content kinds

9. Designing Interface Hierarchies

GuidelineDetail
ShallowAvoid > 2 levels of interface inheritance
CohesiveGroup only fields semantically tied
StableAdding a field to an interface is a breaking change

10. Choosing Interface vs Type

Use InterfaceUse Concrete Type
Multiple kinds share fieldsSingle, specific shape
Need polymorphic queriesNo abstraction needed
Want pagination across kindsPagination per kind

Was this article helpful?