GraphQL Schema TypeScript Generator
graphql-schema-typescript is a utility library for generating TypeScript type definitions directly from GraphQL schema definitions. Unlike client-side code generators such as Apollo-codegen, which focus on types for client queries, this library's primary purpose is to produce type-safe interfaces for GraphQL server-side development, specifically for writing resolvers. The current stable version is 1.6.1. While there isn't a strict release cadence, the project is actively maintained with recent updates to support newer GraphQL versions. Key differentiators include a 1-to-1 mapping from GraphQL types to TypeScript interfaces, conversion of GraphQL descriptions to JSDoc comments, and specialized types for resolver arguments, parent objects, and return values (e.g., `GQLResolver`, `RootQueryToUsersArgs`, `RootQueryToUsersResolver`). It offers both a programmatic API and a command-line interface (CLI) for integration into build workflows, supporting `.gql` and `.graphqls` schema file extensions.
Common errors
-
Error: Cannot find module 'graphql' or its corresponding type declarations.
cause The `graphql` peer dependency is either not installed, or its version is incompatible with `graphql-schema-typescript`.fixInstall the correct `graphql` version as specified in `graphql-schema-typescript`'s `package.json` or README. For example, `npm install graphql@^16.0.0`. -
Error: Schema must contain unique named types but contains multiple types named "YourType"
cause Your GraphQL schema definition has duplicate type names, which is not allowed by the GraphQL specification.fixReview your `.gql` or `.graphqls` schema files (or the schema object passed programmatically) and ensure all type, input, enum, and interface names are unique across the entire schema. Check for accidental re-declarations or issues with schema merging if using multiple files. -
TypeError: Cannot read properties of undefined (reading 'kind') at buildASTSchema
cause The input provided to `buildSchema` (when using the programmatic API) or the schema files provided to the CLI are not valid GraphQL SDL strings or do not represent a parseable schema.fixEnsure that the `schema` argument passed to `generateTypeScriptTypes` is a valid `GraphQLSchema` object, typically created with `buildSchema` from a correct SDL string. If using the CLI, verify that the `--schema` argument points to valid GraphQL schema files (`.gql`, `.graphqls`). -
TS2307: Cannot find module './generated-types' or its corresponding type declarations.
cause The generated TypeScript file (`generated-types.ts` in this example) is not being correctly picked up by your TypeScript compiler or IDE. This can be due to an incorrect `outputPath`, missing `include` in `tsconfig.json`, or the file not existing.fixVerify that the `outputPath` in your `generateTypeScriptTypes` call (or CLI output path) is correct and accessible. Ensure your `tsconfig.json`'s `include` array covers the directory where the types are generated (e.g., `"include": ["./src", "./generated-types.ts"]`). Run the generation script to confirm the file is actually created.
Warnings
- breaking The `graphql` peer dependency has specific version requirements for each major/minor release of `graphql-schema-typescript`. For example, v1.6.x requires `^16.0.0` of `graphql`, while v1.5.x required `^14.0.0` or `^15.0.0`. Using an incompatible `graphql` version will lead to runtime errors or incorrect type generation.
- breaking In version 1.3.1, enum types under the global scope are now generated as TypeScript `enum` instead of `string union` types. This is a breaking change that might affect existing code relying on string union behavior.
- gotcha The default `TParent` and `TResult` types for generated resolvers can be implicitly `any` or inferred based on schema, but v1.2.2 introduced `smartTParent` and `smartTResult` options. If these are set to `true`, `TParent` might become `undefined` (if `rootValueType` is used) or `TResult` will be strongly inferred, which could alter resolver signatures.
- gotcha From v1.2.10 onwards, generated files include `/* eslint-disable */` comments. While this prevents linting errors in generated code, it might override project-specific linting configurations if you wish to apply custom rules to generated files or integrate them more tightly into your linting pipeline.
Install
-
npm install graphql-schema-typescript -
yarn add graphql-schema-typescript -
pnpm add graphql-schema-typescript
Imports
- generateTypeScriptTypes
const { generateTypeScriptTypes } = require('graphql-schema-typescript');import { generateTypeScriptTypes } from 'graphql-schema-typescript'; - GenerateTypescriptOptions
import type { GenerateTypescriptOptions } from 'graphql-schema-typescript';
Quickstart
import { generateTypeScriptTypes } from 'graphql-schema-typescript';
import { buildSchema } from 'graphql';
import * as fs from 'fs/promises';
async function generateTypes() {
const schemaString = `
type Query {
hello(name: String!): String!
users: [User!]!
}
type User {
id: ID!
name: String!
email: String
}
schema {
query: Query
}
`;
const schema = buildSchema(schemaString);
const outputPath = './generated-types.ts';
try {
await generateTypeScriptTypes(schema, outputPath, {
debug: true, // Enable debug logging
contextType: 'MyContextType',
rootValueType: 'MyRootValueType',
smartTParent: true, // Infer TParent type for resolvers
smartTResult: true, // Infer TResult type for resolvers
enumValueSuffix: 'Enum' // Suffix for generated enum types
});
console.log(`Successfully generated TypeScript types to ${outputPath}`);
const generatedContent = await fs.readFile(outputPath, 'utf-8');
console.log('Generated content preview:\n', generatedContent.substring(0, 500), '...');
} catch (err) {
console.error('Error generating types:', err);
process.exit(1);
}
}
generateTypes();