Member-only story
Automating Type Safety: How to Generate TypeScript Types from a GraphQL Schema
Automatically generating TypeScript types based on a GraphQL schema is a powerful way to ensure type safety between your backend and frontend codebases. This can be achieved using various tools, and one of the most popular is graphql-codegen
by The Guild.
Here’s how you can set up GraphQL Code Generator to automatically generate TypeScript types for your GraphQL schema.
Install GraphQL Code Generator
First, you need to install the required packages.
npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations
Configuration
You then need to create a codegen YAML configuration file (codegen.yml
or codegen.json
):
schema: http://localhost:4000/graphql # point to your GraphQL server
generates:
src/generated/graphql.tsx: # Where you want the generated files to go
plugins:
- typescript # For base TypeScript types
- typescript-operations # For operation types (query/mutation/subscription)
In this example, I’ve used the YAML format for the config and pointed it to a local GraphQL server running on http://localhost:4000/graphql
. Adjust the schema
field to point to your GraphQL server.