Search⌘ K
AI Features

Generating Client-Side Types

Explore generating TypeScript types automatically from your GraphQL schema using GraphQL Code Generator. Understand how these generated types and helper functions simplify accessing GraphQL data in React, ensuring consistent client-server data integrity and reducing verbose code.

We'll cover the following...

In the previous lessons, we connect the GraphQL server and our client React application. However, there is still more we can do to improve the code. A GraphQL API’s schema is typed. Can we use those types to create TypeScript types? Yes! Such a thing is possible using GraphQL Code Generator.

GraphQL Code Generator

We’ll use this tool to read data from our server’s GraphQL schema and construct TypeScript types based on what the schema returns. We’ll then be able to remove our types for Book and AllBooksQuery; instead, we’ll use generated types.

We’ll also use this tool to generate helper functions, which will allow us to write much shorter useQuery function calls. We use these helper functions instead of useQuery<AllBooksQuery>(allBooksQuery), which can be quite verbose.

Now, let’s take a look at code generated by GraphQL Code Generator.

Generated types

Over in our src/generated/graphql.tsx file, we have a whole bunch of code that we didn’t write. This code is composed of the automatically generated types built from running GraphQL Code Generator. GraphQL Code Generator looked at the server’s GraphQL schema and our local GraphQL queries and built up a list of types (and even some functions) for us. We can use these in our application to ensure the client-side types match up with what the GraphQL server is providing.

Note: The generated file is quite long because the API we’re using is quite detailed.

GraphQL can be configured to create a generated types file in our chosen directory. We’ve chosen src/generated/graphql.tsx as the address of our generated file. Let’s take a look at it now.

import {ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
    uri: "{{EDUCATIVE_LIVE_VM_URL}}:3000",
    cache: new InMemoryCache(),
}); 

export default client;
Code generated using GraphQL Code Generator