{"id":12763,"library":"graphql-schema-typescript","title":"GraphQL Schema TypeScript Generator","description":"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.","status":"active","version":"1.6.1","language":"javascript","source_language":"en","source_url":"https://github.com/dangcuuson/graphql-schema-typescript","tags":["javascript","typescript"],"install":[{"cmd":"npm install graphql-schema-typescript","lang":"bash","label":"npm"},{"cmd":"yarn add graphql-schema-typescript","lang":"bash","label":"yarn"},{"cmd":"pnpm add graphql-schema-typescript","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for GraphQL schema parsing and manipulation. Specific versions are mandated per graphql-schema-typescript major release.","package":"graphql","optional":false},{"reason":"The library generates TypeScript code and relies on TypeScript for its own development and type definitions.","package":"typescript","optional":false}],"imports":[{"note":"Primary function for programmatic type generation. The library is primarily consumed as an ESM module in modern Node.js/TypeScript environments.","wrong":"const { generateTypeScriptTypes } = require('graphql-schema-typescript');","symbol":"generateTypeScriptTypes","correct":"import { generateTypeScriptTypes } from 'graphql-schema-typescript';"},{"note":"This type defines the configuration options for the `generateTypeScriptTypes` function. Always import types using `import type` for clarity and bundler optimization.","symbol":"GenerateTypescriptOptions","correct":"import type { GenerateTypescriptOptions } from 'graphql-schema-typescript';"}],"quickstart":{"code":"import { generateTypeScriptTypes } from 'graphql-schema-typescript';\nimport { buildSchema } from 'graphql';\nimport * as fs from 'fs/promises';\n\nasync function generateTypes() {\n  const schemaString = `\n    type Query {\n      hello(name: String!): String!\n      users: [User!]!\n    }\n\n    type User {\n      id: ID!\n      name: String!\n      email: String\n    }\n\n    schema {\n      query: Query\n    }\n  `;\n  const schema = buildSchema(schemaString);\n  const outputPath = './generated-types.ts';\n\n  try {\n    await generateTypeScriptTypes(schema, outputPath, {\n      debug: true, // Enable debug logging\n      contextType: 'MyContextType',\n      rootValueType: 'MyRootValueType',\n      smartTParent: true, // Infer TParent type for resolvers\n      smartTResult: true, // Infer TResult type for resolvers\n      enumValueSuffix: 'Enum' // Suffix for generated enum types\n    });\n    console.log(`Successfully generated TypeScript types to ${outputPath}`);\n    const generatedContent = await fs.readFile(outputPath, 'utf-8');\n    console.log('Generated content preview:\\n', generatedContent.substring(0, 500), '...');\n  } catch (err) {\n    console.error('Error generating types:', err);\n    process.exit(1);\n  }\n}\n\ngenerateTypes();\n","lang":"typescript","description":"This quickstart demonstrates how to programmatically generate TypeScript types from a GraphQL schema string, including common configuration options like `smartTParent` and `contextType`. It uses `buildSchema` from `graphql` to create a schema object and writes the output to a file."},"warnings":[{"fix":"Always check the `Compatibility` table in the package's README or `package.json` to ensure your installed `graphql` version matches the `graphql-schema-typescript` peer dependency. Upgrade or downgrade `graphql` as needed (e.g., `npm install graphql@^16.0.0`).","message":"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.","severity":"breaking","affected_versions":">=1.4.0"},{"fix":"Update your code to expect generated enum types where appropriate. If string unions are preferred, consider custom type mapping options or adjusting your schema. For `d.ts` generation, `export const enum` is used.","message":"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.","severity":"breaking","affected_versions":">=1.3.1"},{"fix":"Explicitly set `smartTParent: false` and `smartTResult: false` in `GenerateTypescriptOptions` if you prefer the legacy `any` defaults or require manual type declaration for resolver parent/result types. Otherwise, adjust resolver implementations to match the inferred types.","message":"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.","severity":"gotcha","affected_versions":">=1.2.2"},{"fix":"If you need to apply linting rules to generated files, you can use a post-processing script to remove these comments or configure your linter to ignore specific patterns. Alternatively, rely on the `// eslint-disable` comments and focus linting efforts on handwritten code.","message":"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.","severity":"gotcha","affected_versions":">=1.2.10"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Install the correct `graphql` version as specified in `graphql-schema-typescript`'s `package.json` or README. For example, `npm install graphql@^16.0.0`.","cause":"The `graphql` peer dependency is either not installed, or its version is incompatible with `graphql-schema-typescript`.","error":"Error: Cannot find module 'graphql' or its corresponding type declarations."},{"fix":"Review 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.","cause":"Your GraphQL schema definition has duplicate type names, which is not allowed by the GraphQL specification.","error":"Error: Schema must contain unique named types but contains multiple types named \"YourType\""},{"fix":"Ensure 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`).","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.","error":"TypeError: Cannot read properties of undefined (reading 'kind') at buildASTSchema"},{"fix":"Verify 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.","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.","error":"TS2307: Cannot find module './generated-types' or its corresponding type declarations."}],"ecosystem":"npm"}