GraphQL Schema TypeScript Generator

1.6.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

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.

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();

view raw JSON →