Generate TypeScript Types from GraphQL

4 Jul 2022

We've discussed working with the GraphQL Code Generator before, but let's go back to basics. In this tutorial we'll learn how to automatically generate TypeScript types for our GraphQL schema, and operations.

To get started you'll want to install the GraphQL Code Generator CLI:

npm install --save-dev @graphql-codegen/cli

Now using npx we can run the initializer:

npx graphql-codegen init

This will then ask us about our project, and what exactly features of GraphQL Code Generator we want to use.

Once complete you should now have a file inside of your project directly with the name you specified for the config file. By default this will be called codegen.yml:

overwrite: true
schema: https://api.cartql.com
documents: "./graphql/**/*.{gql,graphql}"
generates:
  types.ts:
    plugins:
      - "typescript"
      - "typescript-operations"

With this we can install install the dependencies added to the package.json, as well as the codegen script:

npm install
npm run codegen

You should now see inside of your project directly you have the file types.ts (or whatever you named it) that contain all of the types for the API you specified.

That's it! You're ready to add GraphQL operations to the directory you specified, and generate the TypeScript types.