Optional fields in GraphQL schema

Hello,

We’ve successfully been using the GraphQL for nearly six months now to generate our website via Gatsby, we’re really happy with it so far.

In our current improvement step, we’re migrating our codebase to Typescript. I’ve experimented using the GraphQL code generator, which also seems to work fine (although I couldn’t get authentication working, so I used another tool to fetch the schema file).

However, pretty much all of the fields of our own content model in the GraphQL schema are marked as optional, despite being marked as required in the content model itself. This causes the resulting typescript fields’ types to (effectively) become string | null | undefined, which works but Typescript makes us set up guards and the like everywhere.

Is this by design? I mean I can imagine that while a field is marked as required, internally it can still be null - that is, required is a client-side validation, not a guarantee that a value is present.

One hacky workaround we can do is to override the maybeValue option in the code generator, but that may be lying / not entirely correct.

3 Likes

I am also experiencing this issue. “Required” is like a special field that only applies to the editor, so how are we supposed to actually enforce non_null.

This effects TypeScript and GraphQL users heavily, and I have not found a solution after a day of searching.

Yeah this is really annoying - i wonder if its by design to stop apps crashing when a preview key is used, even required fields can be missing in that scenario?