Generate TypeScript Types From a GraphQL Schema

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet

It would quickly get out of hand if we had to create TypeScript types for every type in our GraphQL schema. Luckily there are a couple packages from graphql-codegen that we can use to make our lives easier.

We'll create a codegen.yml file where we'll specify our GraphQL schema and choose the location of the types file we want to generate based on the schema.

Then we can create a script in our package.json that runs the codegen.

For more on using TypeScript with AppSync Lambda Resolvers, check out Benoît Bouré blog post: How to use TypeScript with AppSync Lambda Resolvers

Tomasz Łakomy: [0:00] There's a small problem with our listBooks implementation. The problem is that I had to, effectively, recreate the book type from our GraphQL schema. For instance, if I wanted to include another field for the name for the author, I would have to do it in two places. If I'm going to have more Lambda functions in this API, this is going to get out of hand really quickly.

[0:20] It's better to auto-generate TypeScript types from the GraphQL schema. In order to auto-generate our types from the GraphQL schema, we need to install two packages, so @graphql-codegen/cli and @graphql-codegen/typescript. Let me hit Enter and start installing those.

[0:38] After this is done, create a new file in the project and call it codegen.yaml. I'm going to take the liberty of copying and pasting its content. This file is going to take the schema which is defined in the GraphQL directory over here, schema.graphql, and is going to generate TypeScript types based on this schema. Those types are going to be located in the file, which is going to be called books.d.ts.

[1:03] Next up, navigate to package.json, and we're going to add one more NPM script. I'm going to create a script called codegen, which is going to run, GraphQL Codegen. Let me fix the typo and let's give it a shot. Open up the terminal and run, npm run codegen. Apparently, this command did generate the output.

[1:22] Let me navigate to the types folder over here, and let's see the TypeScript types that were generated for us. For instance, here, we can see the type for a book. It's slightly more complicated than the type that we had before. The bottom line is, is that we didn't have to create this type our self. It's much easier and much quicker for the computer to generate those types for us.

[1:44] In fact, let us go back to our Lambda function. I'm going to delete the type for a book. We are no longer going to need that. Instead, I'm going to import this type from the file that we have just created. We can see that TypeScript has not found any errors, and we can continue using this auto-generated type in our code.