I am learning graphql, and want to find out how to use the type of object which we are getting in result.
as we are requesting like
const GET_CHARACTERS = gql`
query {
characters{
results{
id
name
image
gender
}
}
}
`
so in the result we got the object same as it is
but can we get the type defination of the so we don’t have to make own type
or we ignore using any cause it is annoying to mention the thing which we have mentioned back in this query also
How can we get the Type of the mention object by graphql
So we can use it as typescript type
2
Answers
To automatically generate
TypeScript
types for the result of a GraphQL query, you can use tools like Apollo Client’scodegen
feature or thegraphql-codegen
library. These tools can analyze your GraphQL queries and generate TypeScript types based on the schema of your GraphQL server.I struggled with the same problem and didn’t find anything else but graphql-zeus library. I almost got it working when I ended up having this issue: https://github.com/graphql-editor/graphql-zeus/issues/322
So I wrote my own similar typescript types because I like to have strong typings. It wasn’t an easy or quick task so I hope someone finds this useful 🙂 It’s used something like this:
It’s a somewhat verbose but it’s worth it.
The implementation can be used with only using the Projection and Intersection types but I included a few helper/wrapper functions that I’m using. It’s a bit of a monster but here it is:
Like said, I’m using Apollo so there might be some Apollo specific stuff there but I guess it can be adjusted pretty easily. Hope this helps.
Edit: I probably need to note that I’m generating and publishing the graphql-codegen types in the backend so that’s why I only get the types for my objects but not types for the gql response objects. So my solution might not be optimal/required for OP but maybe someone else.