Generate sub types for graphql-codegen
Asked Answered
S

1

12

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?

Spillage answered 31/8, 2022 at 15:45 Comment(2)
Hey did you land up getting this right? I have to do the samePsalmist
No, didn't have time to wait for a solution, so went ahead and changed all places where types were referenced in a single big git commit.Spillage
O
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).

Organzine answered 4/5, 2023 at 16:30 Comment(3)
But this way, the ViewerFieldsFragment is not explicitly used in MyDataQuery and an explicit cast with as will be necessary. I have the same issue and I still haven't found a solutionTied
@Tied did you land up finding a solution without having to refactor?Psalmist
I've done something like this : .pipe(map(res => res.data.parcelsGroup?.nodes ?? []). The issue with typing was the | undefined so I use the ?? operator to remove the possibility of it being undefined.Tied

© 2022 - 2024 — McMap. All rights reserved.