Automate your Typescript’s Type generation
GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data.
We no longer have to play the guessing game, as we did with REST. It’s strongly-typed. Given a query, tooling can ensure that the query is both syntactically correct and valid within the GraphQL type system before execution.
As Typescript is a typed language it’s a perfect match for GraphQL. By using them together you are making sure that the right types are consistent across your BE and FE.
Why do we have to manually define our Typescript interfaces then? Manual work means human errors can happen. With that motivation
graphql-codegen was born.
GraphQL Code Generator is a CLI tool that can generate TypeScript typings out of a GraphQL schema. When we develop a GraphQL backend, there would be many instances where we would find ourselves writing the same things which are already described by the GraphQL schema, only in a different format; for example: resolver signatures, MongoDB models, Angular services etc.
In summary: it’s a CLI tool that will do all the heavy lifting for us. Let’s take a deep dive into it and see how easy it is to use it to produce our first query using
Let’s start by installing the GraphQL library:
yarn add graphql npm install — save graphql
Next, we need to add the
yarn add -D @graphql-codegen/cli npm install --save-dev @graphql-codegen/cli
In this lesson, we are going to learn how to GraphQL Code Generator with TypeScript and GraphQL. At first TypeScript and GraphQL seem like a match made in heaven. Where GraphQL Code Generator was magically creating TS types for me whenever I changed my GraphQL schema.