Typed Resolvers & Operations From SDL
GraphQL Codegen
Generate TypeScript types for resolvers and client operations from your GraphQL schema so resolver signatures stay in sync with the contract.
What you'll learn
- Install @graphql-codegen/cli and resolver plugins
- Configure codegen.yml or codegen.ts
- Run codegen as part of the build
Hand-writing resolver types is error-prone — change the schema and your TS types silently drift. graphql-code-generator reads the SDL and emits matching TypeScript.
Install
npm install -D @graphql-codegen/cli \
@graphql-codegen/typescript \
@graphql-codegen/typescript-resolvers Configure
// codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: './schema.graphql',
generates: {
'./src/generated/graphql.ts': {
plugins: ['typescript', 'typescript-resolvers'],
config: {
contextType: 'FastifyRequest',
useIndexSignature: true,
},
},
},
}
export default config Run npx graphql-codegen to produce src/generated/graphql.ts with Resolvers<Context> and per-field types.
Type Your Resolvers
import type { Resolvers } from './generated/graphql.js'
export const resolvers: Resolvers = {
Query: {
user: async (_parent, args, ctx) => {
return ctx.server.db.user.findUnique({ where: { id: args.id } })
},
},
} If you rename User.email to User.emailAddress in the schema, the compiler flags every resolver that returns the wrong shape.
Wire Into The Build
Add codegen to your scripts so it runs in CI before tsc:
{
"scripts": {
"codegen": "graphql-codegen",
"build": "npm run codegen && tsc -p ."
}
} Commit the generated file or generate it in CI — either is fine, but commit only one source of truth.
undici — The Modern HTTP Client →