Graphql-code-generator: Why does typescript-operations generate every filed as mandatory with <Maybe>?

Created on 19 Sep 2019  路  8Comments  路  Source: dotansimha/graphql-code-generator

I have a type "personAlias", and query for it

personAlias {
        firstName
        lastName
        gender {
          code
          description
        }
      }

Type that gets generated for it looks like

export type PersonAliasType = {
   __typename?: 'PersonAliasType',
  firstName?: Maybe<Scalars['String']>,
  gender?: Maybe<RefDataType>,
  lastName?: Maybe<Scalars['String']>,
};

Notice that gender is optional.
But in the end query it looks like

personAlias: (
        { __typename?: 'PersonAliasType' }
        & Pick<Types.PersonAliasType, 'firstName' | 'lastName'>
        & { gender: Types.Maybe<(
          { __typename?: 'RefDataType' }
          & Pick<Types.RefDataType, 'code' | 'description'>
        )> }
      )

Which makes it mandatory, which causes conflicts. Why? I have set as avoidOptionals: false

waiting-for-answer

Most helpful comment

Also, note that you can try to add avoidOptionals: true and it will avoid using ? while generating.

All 8 comments

Can you share your schema please?

@n1ru4l

type PersonAliasType {
  dateOfBirth: DateTime
  firstName: String
  gender: RefDataType
  id: String!
  lastName: String
}

type RefDataType {
  code: String!
  description: String
}

The types are Maybe types cause they could be null according to your schema

But null doesn't mean that they they are optional, it just means that they can exist with value of null. You can't have no key at all

Could you please provide a minimal reproduction using the code sandbox template (https://codesandbox.io/s/github/dotansimha/graphql-code-generator-issue-sandbox-template)?

@TheWWWorm In GraphQL, there are nullables and nonnullables. If you return undefined or null, it is considered as null. AFAIK, GraphQL Client returns null for undefined fields. But it would be great if you show your problem using the sandbox template as @n1ru4l asked.

Also, note that you can try to add avoidOptionals: true and it will avoid using ? while generating.

Closing. @TheWWWorm feel free to re-open/comment if this is still relevant.

Was this page helpful?
0 / 5 - 0 ratings