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?
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).
I also had this problem and I'm not sure if this existed when the question was asked but on the graphql-codegen typescript docs there is an option for extractAllFieldsToTypes which does this.
In your config set it to true:
config: {
extractAllFieldsToTypes: true, <--
enumsAsTypes: false,
namingConvention: "keep",
omitOperationSuffix: true,
declarationKind: "interface",
avoidOptionals: {
field: true,
},
nonOptionalTypename: true,
skipTypeNameForRoot: true,
onlyOperationTypes: true,
},
And it will generate types for each result separately for each query like Apollo codegen did.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With