Skip to content

Support @required and @optional directives #10453

@aaronadamsCA

Description

@aaronadamsCA

Is your feature request related to a problem? Please describe.

I'd like to add built-in support for any method that could generate the following TypeScript types from a schema for use by a client:

export type MyInput = {
  a?: InputMaybe<Scalars['String']['input']>;
  b?: Scalars['String']['input'];
  c: InputMaybe<Scalars['String']['input']>;
  d: Scalars['String']['input'];
};

Describe the solution you'd like

The best proposal I've seen uses @required and @optional input directives, as described in graphql/graphql-spec#872:

"""
This input is optional, not nullable.
If the client insists on sending an explicit null value, the behavior is undefined.
"""
directive @optional on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION

"""
This input is nullable, not optional.
If the client insists on omitting the input value, the behavior is undefined.
"""
directive @required on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION

input MyInput {
  a: String
  b: String @optional
  c: String @required
  d: String!
}

This addresses a very common concern, and since it only uses directives, it's completely forward- and backward-compatible and doesn't require any changes to the GraphQL spec.

My suggestion is to support the above with a new TypeScript plugin option:

export default {
  generates: {
    "path/to/file": {
      config: {
        directiveArgumentAndInputFieldNarrowing: {
          nonNullable: "optional",
          nonOptional: "required",
        },
      },
    },
  },
} satisfies CodegenConfig;

Describe alternatives you've considered

No response

Any additional important details?

If we could agree on the right approach, I'd be happy to try implementing this myself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions