SkillByAIOpen interactive version →

Lesson 18 / 25

Code Generation and Typed Operations

Types from the schema.

Generate types for every operation

Because the schema is typed, tools such as GraphQL Code Generator (TypeScript and other languages), Apollo iOS and Kotlin, or gqlgen for Go servers can generate types for the schema and for each operation's result and variables. The compiler then catches typos in field names and mismatched variables, and schema changes surface as build errors in clients. Run codegen in CI against the published schema.

A GraphQL Code Generator config

codegen.ts (a sketch; check plugin and preset names for your version).

import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "schema.graphql",
  documents: ["src/**/*.tsx"],
  generates: {
    "src/gql/": {
      preset: "client",      // typed graphql() function and result types
    },
  },
};

export default config;

Fail the build on schema drift

Regenerating types in CI turns a breaking schema change into a failing build instead of a production bug.

Quick check: What does GraphQL code generation provide?

  • Typed results and variables for operations, derived from the schema
  • A new database
  • Faster networks
  • Automatic authentication
Answer

Typed results and variables for operations, derived from the schema — Compile-time safety.