An extension for the graphq-tag
library used by many graphql clients that infers query return types, removing the need for client-side type code-gen.
-
Install
typed-graphql-tag
npm install --save typed-graphql-tag
-
Generate graphql server types - if you already have these, skip this step
Install graphql-codegen
npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescript
Create codegen.yml
# codegen.yml schema: schema.graphql generates: src/graphql-types.ts: - typescript
Generate server types
npx graphql-codegen
-
Create typed-graphql-tag client
// gql-tag.ts import { createGqlTag } from 'typed-graphql-tag'; import { Query, Mutation } from './graphql-types'; export const gql = createGqlTag<Query, Mutation>();
-
Use in application (apollo example)
import { useQuery } from '@apollo/client'; import { gql } from './gql-tag'; // `data` is fully typed according to our `schema.graphql` const { data } = useQuery( gql(` query UserQuery { id name posts { id description } } `) );