Describe the bug
With the latest versions, I am getting some errors in my generated typescript files.
Notice the final | | | | | | | | on the following generated code:
export type PostMdxFragment = (
Pick<Mdx, 'id' | 'body' | 'excerpt'>
& { fields: Maybe<Pick<MdxFields, 'slug'>>, frontmatter: Maybe<(
Pick<MdxFrontmatter, 'categories' | 'date' | 'dateFormatted' | 'last_modified_at' | 'layout' | 'tags' | 'title'>
& { image: Maybe<(
Pick<File, 'publicURL'>
& { childImageSharp: Maybe<{ fluid: Maybe<Pick<ImageSharpFluid, 'presentationWidth'>
& GatsbyImageSharpFluid_WithWebpFragment
> }> }
)> }
)>, file: Maybe<Pick<File, 'base'> | | | | | | | | > }
);
To Reproduce
yarn to install dependenciesyarn develop to startyarn codegencheck the generated "src\utils\graphql.generated.ts" file, and look for the bit in the example above.
My GraphQL schema:
Mostly inferred from my typescript code, but after running yarn develop from the steps above, you can access it via http://localhost:8000/__graphql
(Inferred from typescript)
codegen.yml config file:overwrite: true
schema: 'http://localhost:8000/___graphql'
documents:
- ./src/**/*.{ts,tsx}
- ./node_modules/gatsby-*/**/*.js
generates:
src/utils/graphql.generated.ts:
config:
skipTypename: true
enumsAsTypes: true
plugins:
- 'typescript'
- 'typescript-operations'
# - "typescript-react-apollo"
# ./graphql.schema.json:
# plugins:
# - "introspection"
Expected behavior
Generate typescript code without errors!
Environment:
@graphql-codegen/...: 1.6.1This should be fixed by https://github.com/dotansimha/graphql-code-generator/pull/2490
Nevertheless, I would advise you to add a __typename selection field to your file SelectionSet in order to determine which type you receive.
Wow, that was a fast fix indeed, thank you very much!!
Nevertheless, I would advise you to add a
__typenameselection field to yourfileSelectionSet in order to determine which type you receive.
Any specific reason as to do this? I ask this as so far I haven't actually needed this!
It seems like file returns a union/interface. Therefore you should probably use the __typename property to distinguish possible return values. IDK about Gatsby, but you only added a selection set for the File type. How would you handle different results?
by doing something like
{
field {
__typename
... on File {
base
}
}
}
you can do the following in your code
if (field.__typename === "File") {
field.base // this field is available
} else {
// type is not covered by fragments do sth else
}
However, this is not enforced, just a practice that I follow.
Fixed in 1.8.0 馃殌
Just tested and it's working fine now! Thanks!! 馃槃
Most helpful comment
This should be fixed by https://github.com/dotansimha/graphql-code-generator/pull/2490
Nevertheless, I would advise you to add a
__typenameselection field to yourfileSelectionSet in order to determine which type you receive.