84

Is it possible to use inheritance with GraphQL input types?

Something like that (this, of course, doesn't work with input types):

interface UserInputInterface {
  firstName: String
  lastName: String
}

input UserInput implements UserInputInterface {
  password: String!
}

input UserChangesInput implements UserInputInterface {
  id: ID!
  password: String
}
3
  • 1
    Have you ever figured out answer to your question? I'm facing the exact same one!
    – LB2
    Commented May 2, 2017 at 19:46
  • 3
    @LB2 unfortunately not, I'm keeping 2 separate types at the moment repeating properties.
    – kyrisu
    Commented May 3, 2017 at 9:29
  • Thanks! I'm trying to represent a boolean expression (much like SQL's WHERE clause), and without inheritance, it seems impossible to express an arbitrary boolean expression without possibility of syntax-matching nonsense. Bummer that it's not part of the language.
    – LB2
    Commented May 3, 2017 at 21:19

4 Answers 4

69

No, the spec does not allow input types to implement interfaces. And GraphQL type system in general does not define any form of inheritance (the extends keyword adds fields to an existing type, and isn't for inheritance). The spec is intentionally constrained to stay simple. This means that you're stuck repeating fields across input types.

That said, depending on the way you construct your schema, you could build some kind of type transformer that appends the common fields programmatically based on some meta-data, e.g. a directive. Here's one such implementation.

Better yet, you might be able to solve your problem via composition (always keep composition over inheritance in mind). E.g.

input Name {
  firstName: String
  lastName: String
}

input UserInput {
  name: Name
  password: String!
}

input UserChangesInput {
  name: Name
  id: ID!
  password: String
}

The client now has to send an object a level deeper, but that doesn't sound like much of a price for avoiding big repeating chunks. It might actually be good for the client as well, as they can now have common logic for building names, regardless of the query/mutation using them.

In this example, where it's only 2 simple fields, this approach is an overkill, but in general - I'd say it's the way to go.

2
  • 1
    Could your example be "extended" further by using the second type in the third one? input userChangesInput { userInput: UserInput, id: ID! } ? Commented Aug 17, 2019 at 14:55
  • @WhatWouldBeCool Of course, you can compose the types freely.
    – kaqqao
    Commented Aug 17, 2019 at 16:44
17

Starting with the June2018 stable version of the GraphQL spec, an Input Object type can extend another Input Object type:

Input object type extensions are used to represent an input object type which has been extended from some original input object type.

This isn't inheritance per se; you can only extend the base type, not create new types based on it:

extend input MyInput {
  NewField: String
}

Note there is no name for the new type; the existing MyInput type is extended.

The JavaScript reference implementation has implemented Input Object extensions in GraphQL.js v14 (June 2018), though it's unclear how to actually pass the extended input fields to a query without getting an error.

For actual type inheritance, see the graphql-s2s library.

1
  • @kaqqao ok, I would now say that both answers are valuable choices, so have upvoted both. I do like your composition approach, but for cases of adding a few fields, the new extends keyword seems like a simpler approach. Commented Aug 17, 2019 at 14:53
4

It's doable using a custom directive.

Code Summary

const typeDefs = gql`
  directive @inherits(type: String!) on OBJECT

  type Car {
    manufacturer: String
    color: String
  }
  
  type Tesla @inherits(type: "Car") {
    manufacturer: String
    papa: String
    model: String
  }
  
  type Query {
    tesla: Tesla
  }
`;

const resolvers = {
    Query: {
        tesla: () => ({ model: 'S' }),
    },
    Car: {
        manufacturer: () => 'Ford',
        color: () => 'Orange',
    },
    Tesla: {
        manufacturer: () => 'Tesla, Inc',
        papa: () => 'Elon',
    },
};

class InheritsDirective extends SchemaDirectiveVisitor {
    visitObject(type) {
        const fields = type.getFields();
        const baseType = this.schema.getTypeMap()[this.args.type];
        Object.entries(baseType.getFields()).forEach(([name, field]) => {
            if (fields[name] === undefined) {
                fields[name] = { ...field };
            }
        });
    }
}

const schemaDirectives = {
    inherits: InheritsDirective,
};

Query:

query {
  tesla {
    manufacturer
    papa
    color
    model
  }
}

Output:

{
  "data": {
    "tesla": {
      "manufacturer": "Tesla, Inc",
      "papa": "Elon",
      "color": "Orange",
      "model": "S",
    }
  }
}

Working example at https://github.com/jeanbmar/graphql-inherits.

1

If you came here looking for an explanation for the "implements", keyword, here it is:

An object type must be a super‐set of all interfaces it implements. The object type must include a field of the same name for every field defined in an interface.

(Excerpt taken from the June 2018 GraphQL spec.)

Here's an example


interface Foo {
  id: ID!
  foo: Int!
}

type Bar implements Foo @entity {
  id: ID!;
  foo: Int!;
  bar: Int!;
}

So the Bar type doesn't inherit from the Foo interface, but it implements it. The former must include all the fields that are listed in the latter.

I think that this is a nice way to annotate types that should be like other types.

1
  • 3
    As stated by the question, the "implements" keyword will only work with types and not with inputs Commented Sep 22, 2021 at 22:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.