Search code examples
typescriptgraphqlapollo-clientcode-generation

Typescript and Graphql Fragments


I use codegen to generate TS types and I use Apollo client to send queries to server.

when I generate code for the following example, Typescript dosen't know that people has firstName and lastName fields, It only knows that avatar field exists. If I remove fragment and move fields directly to query all fields are usable.

What should I do to support fragments correctly?

fragments/person.graphql

fragment NameParts on Person {
  firstName
  lastName
}

queries/person.ts

import { graphql } from '@/gql'

export const getPersonDocument = graphql(`
   query GetPerson {
     people(id: "7") {
       ...NameParts
       avatar(size: LARGE)
     }
   }
`)

'@/gql' is the output directory of codegen


Solution

  • I set fragmentMasking: false to fix the problem

      generates: {
        './src/gql/': {
          preset: 'client',
          presetConfig: {
            fragmentMasking: false,
          },
        },
      },