Search code examples
typescriptgraphqlcode-generation

Can graphql codegen automatically generate types for hooks' result data field?


I'm using graphql codegen hooks, which results are of the type: ApolloReactCommon.QueryResult, meaning it's an object that has data, loading and error fields.

Most generally, I'll use the data in other components, where I need to define its type. I currently need to write something like this to get data type:

type MyPost = MyPostQueryHookResult['data']

I would have expected to get this MyPost type created for me. Is there a way to have it generated automatically?

My config:

generates:
  src/generated/graphql.tsx:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"
    config:
      withHooks: true

Solution

  • The best way to do this is to use fragments when building the query. Types will be generated for each fragment and they can then be used directly.

    source: from the main contributor of graphql-codegen