GraphQL/TypeScript: Create Types when not Provided


Recently, I kicked off a project using GraphQL and needed the TypeScript types for the GraphQL API. However, they were not included in the project. It’s surprisingly easy to generate these types, but seemingly hard to find a simple “Here’s how you do it” example.

In this case, install the required packages:

pnpm i -D @babel/core@^7 @graphql-codegen/cli
npx graphql-codegen init

The init asks questions about your project. Here’s how I responded:

NOTE: Originally, I named the config codegen.ts (the defaulted value), but that led to this weird error:

error TS5095: Option 'preserveValueImports' can only be used when 'module' is set to 'es2015' or later

Next, tweak your configuration based on your GraphQL server. If your API is private and requires authentication, add the appropriate header:

              Authorization: '...[private]...'
            - typescript

Now running

pnpm run codegen

generates ~3000 lines of beautiful types for my project:

/** A paginated list of Podcast items. */
export type PodcastList = {
  __typename?: 'PodcastList';
  cursorInfo?: Maybe<CursorInfo>;
  /** A list of Podcast items. */
  data: Array<Podcast>;
  /** Pagination information about the list of items. */
  paginatorInfo?: Maybe<PaginatorInfo>;