How to Generate TypeScript Types From GraphQL

How to Generate TypeScript Types From GraphQL

Automatically keeping your types in sync between your frontend and backend
Ferenc Almasi β€’ Last updated 2021 November 11 β€’ Read time 4 min read
Learn how you can generate TypeScript types from a GraphQL schema to automatically keep the types in sync between your backend and frontend.
  • twitter
  • facebook
TypeScript

If you are using both TypeScript and GraphQL in your projects, you may have found yourself trying to keep your TypeScript types in sync with your GraphQL schema. If you have been doing this manually until now, then this article will be for you.

We will have a look into how you can automatically generate your TypeScript types based on your GraphQL schema, so you never have to worry about again manually updating your interfaces. To get the GraphQL schema converted into TypeScript types, we will need to go over the following steps:


Exporting the GraphQL schema

In order to get the GraphQL schema definition, we will be using a third-party CLI tool, called graphql-code-generator. This will be responsible for both getting the schema, and generating the TypeScript type definitions.

If you head over to the homepage of the CLI tool, you can try out the live demo to see how the types are being generated.

GraphQL Code Generator Live Preview

Setting up GraphQL code generator

To set up the GraphQL code generator, we’re going to need to install some dependencies, namely the following:

npm i --save graphql
npm i --save-dev @graphql-codegen/cli
npm i --save-dev @graphql-codegen/typescript

Try to avoid installing the dependencies globally as they can cause issues because of duplications.

If you don’t have the graphql package installed already, make sure you install it first before trying to add graphql-codegen as it relies on the core GraphQL package. Without it, it won’t be able to generate the types for TypeScript.

The other two packages are related to the code generation CLI, one is the CLI tool itself, the other is a plugin that we want to use. Since we want to convert the schema into TypeScript types, we need to pull in the TypeScript plugin.

Lastly, you want to add a codegen.yml or codegen.json config file to your project directory, as this is what GraphQL codegen will look for when trying to fetch the schema and convert it into TS types:

Copied to clipboard!
schema: http://localhost:3000/graphql
generates:
  ./types.d.ts:
    plugins:
      - typescript
codegen.yml

It requires setting a schema field that will tell GraphQL codegen where to look for your schema. Under the generates field, we also need to define a path where we want the types to be generated. In this case, it will be generated into the root of the project folder under the name types.d.ts. And since we want to generate TypeScript types, we need to tell codegen to use the typescript plugin.


Generating TypeScript Types Based on GraphQL Schema

Once all is set up, you will be able to run graphql-codegen to generate the TypeScript types based on your yml file, or add it as script into your package.json:

Copied to clipboard!
{
    "scripts": {
        "generate-types": "graphql-codegen"
    }
}
package.json

Then you will be able to execute this command using npm run generate-types. You can also add it to your development workflow to generate types if you start your dev server, that way, you will ensure you always have the latest types, without having to periodically rerun this command. You can also add it to your CI environment to do verifications.

Once you run codegen, you will see that apart from your TypeScript types, it will also generate some built-in custom scalars and types, such as the following:

Copied to clipboard!
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
export type Scalars = {
  ID: string;
  String: string;
  Boolean: boolean;
  Int: number;
  Float: number;
  Date: any;
};
types.ts

These will be used as base types. For example, see how the following GraphQL schema translates to scalars in TypeScript:

GraphQL schema converted to TypeScript types
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Conclusion

In conclusion, the GraphQL code generator CLI tool makes it super easy for us to keep the GraphQL schema and the TypeScript type definitions in sync without having to worry about updating it manually. Of course, there are multiple solutions to every problem. Apart from the GraphQL code generator CLI, you could also use:

Have you used one of the tools before in your projects? What are your thoughts? Let us know in the comments below! Thank you for reading through, happy coding!

How to Get Started With TypeScript
  • twitter
  • facebook
TypeScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.