Is it possible to implement multiple interfaces in GraphQL?

Yes. As outlined in the spec:

An object type may declare that it implements one or more unique interfaces.

Keep in mind that the resulting object must be a “super-set of all interfaces it implements” — it must implement all the fields each interface has and these fields cannot conflict. For example, if Interface A and Interface B both have a field called something, the type of that field must be the same for both interfaces in order for an Object Type to implement both interfaces.

Here’s a simple example that you can open in CodeSandbox and play around with.

Note: As others have pointed out, using a comma to separate the interfaces is no longer supported — please use an & (ampersand) instead.

const { ApolloServer, gql } = require("apollo-server");

const typeDefs = gql`
  type Query {
    someAnimal: Animal!
    someBird: Bird!
  }

  interface Bird {
    wingspan: Int!
  }

  interface Animal {
    speed: Int!
  }

  type Swallow implements Animal & Bird {
    wingspan: Int!
    speed: Int!
  }
`;

const resolvers = {
  Query: {
    someAnimal: (root, args, context) => {
      return { wingspan: 7, speed: 24 };
    },
    someBird: (root, args, context) => {
      return { wingspan: 6, speed: 25 };
    }
  },
  Bird: {
    __resolveType: () => "Swallow"
  },
  Animal: {
    __resolveType: () => "Swallow"
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

Please note that the spec now also allows interfaces to implement other interfaces.

When defining an interface that implements another interface, the implementing interface must define each field that is specified by the implemented interface… Transitively implemented interfaces (interfaces implemented by the interface that is being implemented) must also be defined on an implementing type or interface.

In GraphQL.js, this is supported as of version 15.0.0.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)