Graphql-code-generator: TypeScript types generates optional keys for nullable keys

Created on 29 Jan 2020  路  2Comments  路  Source: dotansimha/graphql-code-generator

btw awesome library!
When you go to https://graphql-code-generator.com/ and use TypeScript. Then you alter the last item in the schema definition like:

type ChatMessage implements Node {
  id: ID!
  content: String
  time: Date!
  user: User!
}

So now content is a nullable field. When you create the types it will type it like:

export type ChatMessage = Node & {
   __typename?: 'ChatMessage',
  id: Scalars['ID'],
  content?: Maybe<Scalars['String']>,
  time: Scalars['Date'],
  user: User,
};

But that means content can be string | null | undefined while in GraphQL we make sure keys are never undefined (so string | null) this type is telling us it is possible. I thought it would be:

export type ChatMessage = Node & {
   __typename?: 'ChatMessage',
  id: Scalars['ID'],
  content: Maybe<Scalars['String']>,
  time: Scalars['Date'],
  user: User,
};

What is your opinion about this? It gives us weird constructions because of this undefined | null.

Most helpful comment

https://graphql-code-generator.com/docs/plugins/typescript#avoidoptionals-boolean-default-value-false
You can use avoidOptionals to make all of them non-optional.
Does this work for you?

All 2 comments

https://graphql-code-generator.com/docs/plugins/typescript#avoidoptionals-boolean-default-value-false
You can use avoidOptionals to make all of them non-optional.
Does this work for you?

Ah, so this has been done to set it in client-side part as non-optional and have the real truth and on server-side to avoid having to transform undefined as null everywhere (our backends not always give all keys back). This will work! Great Arda!

Was this page helpful?
0 / 5 - 0 ratings