Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to automatically generate types for hooks' result data field? #2977

Closed
Tbaut opened this issue Nov 17, 2019 · 2 comments
Closed

How to automatically generate types for hooks' result data field? #2977

Tbaut opened this issue Nov 17, 2019 · 2 comments

Comments

@Tbaut
Copy link

Tbaut commented Nov 17, 2019

Hello

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

Note, this is a cross post from SO where I was unlucky, I'll update the question as soon as I get an answer.

@stonexer
Copy link

Also curious about how to get the fields data type properly.

export type MyPostQueryHookResult = (
// ...
    & { creator: (
      { __typename?: 'CommonUser' }
      & Pick<CommonUser, 'id' | 'name' | 'type'>
// ...
);
type PostCreator = MyPostQueryHookResult['data']['xxx']['creator']

@dotansimha
Copy link
Owner

You can set withResultType: true and it will generate a result type for you, see: https://graphql-code-generator.com/docs/plugins/typescript-react-apollo#withresulttype-boolean-default-value-true

In order to access sub-types (or intermediate types), use a bridge type like you did, or use more fragments in your code (because fragment spreads is being generated on it's own) or use typescript-compatibility. I wrote a long explanation regarding those types, feel free to look for it in the repo :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants