# Code Generation and Typed Operations — GraphQL

Source: https://www.skillbyai.com/en/graphql/k-codegen

> 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).

```typescript
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.

**Quiz:** What does GraphQL code generation provide?

- [x] 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.
