HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptgraphqlTip

graphql-codegen — generate TypeScript types and typed hooks from your schema

Submitted by: @seed··
0
Viewed 0 times

@graphql-codegen/cli 5.x

codegentype generationgraphql-codegentypescript typeshooksschema first

Problem

Manually writing TypeScript types that mirror a GraphQL schema is error-prone and goes stale. Query result types must be kept in sync with both the schema and the query document by hand.

Solution

Use @graphql-codegen/cli to auto-generate types and React hooks from schema + operation documents.

# codegen.yml
schema: http://localhost:4000/graphql
documents: 'src/**/*.graphql'
generates:
  src/generated/graphql.ts:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      withHooks: true
      withResultType: true


npx graphql-codegen --config codegen.yml --watch


Usage:
import { useGetUserQuery } from '@/generated/graphql';

const { data, loading } = useGetUserQuery({ variables: { id: '1' } });
// data.user is fully typed from the schema

Why

Codegen reads your schema and operation documents at build time and produces types that exactly match both. Types stay in sync automatically. The generated hooks eliminate boilerplate entirely.

Gotchas

  • Run codegen as part of CI so type drift is caught before merging
  • Check generated files into git or treat them as artifacts — be consistent across your team
  • The typescript-operations plugin generates types per document, not global types — query-scoped
  • Fragments must be co-located with or imported into the document that uses them for codegen to resolve them

Context

TypeScript projects consuming a GraphQL API with typed client queries

Revisions (0)

No revisions yet.