How to Generate TypeScript Types from GraphQL Easily
Use
GraphQL Code Generator to automatically create TypeScript types from your GraphQL schema and queries. Install it with npm, configure a codegen.yml file, then run graphql-codegen to generate the types.Syntax
The main steps to generate TypeScript types from GraphQL are:
- Install the code generator tool.
- Create a configuration file specifying your schema and documents.
- Run the generator command to produce TypeScript files.
The configuration file usually includes:
schema: Path or URL to your GraphQL schema.documents: Path to your GraphQL queries or mutations.generates: Output file and plugins to use (liketypescript).
bash
npm install -D @graphql-codegen/cli
# Create codegen.yml
schema: ./schema.graphql
documents: ./src/**/*.graphql
generates:
./src/generated/graphql.ts:
plugins:
- typescript
- typescript-operations
# Run codegen
npx graphql-codegenExample
This example shows how to generate TypeScript types from a simple GraphQL schema and query.
plaintext
# schema.graphql """ type Query { hello: String } """ # query.graphql query SayHello { hello } # codegen.yml schema: ./schema.graphql documents: ./query.graphql generates: ./generated/types.ts: plugins: - typescript - typescript-operations # Run the command npx graphql-codegen
Output
export type SayHelloQuery = {
__typename?: 'Query';
hello?: string | null;
};
Common Pitfalls
Common mistakes when generating TypeScript types from GraphQL include:
- Not installing required plugins like
typescript-operationsfor query types. - Incorrect paths in
schemaordocumentsfields causing no types to generate. - Running the generator without a config file or with syntax errors in it.
- Forgetting to include
typescriptplugin to generate base types.
Always check your config file syntax and paths carefully.
yaml
## Wrong config example (missing plugins)
schema: ./schema.graphql
documents: ./queries.graphql
generates:
./types.ts:
plugins: []
## Correct config example
schema: ./schema.graphql
documents: ./queries.graphql
generates:
./types.ts:
plugins:
- typescript
- typescript-operationsQuick Reference
| Step | Command / Config | Description |
|---|---|---|
| 1 | npm install -D @graphql-codegen/cli | Install GraphQL Code Generator |
| 2 | Create codegen.yml | Configure schema, documents, output, and plugins |
| 3 | npx graphql-codegen | Run generator to create TypeScript types |
| 4 | Import generated types | Use types in your TypeScript code for safety |
Key Takeaways
Use GraphQL Code Generator to automate TypeScript type creation from your GraphQL schema and queries.
Always configure schema, documents, and plugins correctly in your codegen.yml file.
Run the generator command after setup to produce up-to-date TypeScript types.
Check for missing plugins or wrong paths if types do not generate as expected.
Import and use the generated types in your code for safer GraphQL operations.