8

I'm using the typescript-operations from graphql-codegen library. But I'm coming from the Apollo deprecated codegen and was loving how they exported types.

for a query like this

query MyData {
  viewer {
    id
    username
  }
}

I would get this from the apollo-tooling codegen:

export type MyDataQuery_viewer = {
  __typename: 'Viewer';
  id: number;
  username: string;
}
export type MyDataQuery = {
  __typename: 'Query',
  viewer?: MyDataQuery_viewer;
}

but in graphql-codegen I'm getting this instead:

export type MyDataQuery = {
  __typename: 'Query',
  viewer?: {
    __typename: 'Viewer';
    id: number;
    username: string;
  };
}

Does there exist any configuration to graphql-codegen that would give me a type of all nested objects instead of having everything defined in a single type?

Jeggy
  • 1,474
  • 1
  • 19
  • 35

1 Answers1

1

graphql-codegen will generate separate types for fragments by default, so that's how I solve this issue:

fragment ViewerFields on Viewer {
  id
  username
}

query MyData {
  viewer {
    ...ViewerFields
  }
}

Will generate

export type ViewerFieldsFragment = {
  __typename: 'Viewer';
  id: number;
  username: string;
}

export type MyDataQuery = {
  __typename: 'Query',
  viewer?: {
    __typename: 'Viewer';
    id: number;
    username: string;
  }
}

And you can use ViewerFieldsFragment in your code. You can change the Fragment suffix if you want with the omitOperationSuffix configuration option for the operations plugin (which the typescript-operations plugin uses behind-the-scenes).