GraphQL API with TypeScript
In this page:
Core Concept
A typed GraphQL API keeps its TypeScript resolver types in sync with its GraphQL schema, so a resolver that returns the wrong shape for a field is caught at compile time instead of producing a confusing runtime GraphQL error.
Example: Core Concept
interface User {
id: string;
name: string;
}
// A resolver returning an incomplete User object is a compile-time error.
function resolveUser(): User {
return { id: "1", name: "Ravi" };
}
console.log(resolveUser());
Basic Setup
A basic setup uses a code generator (like GraphQL Code Generator) that reads your .graphql schema files and produces matching TypeScript types and resolver signatures automatically.
Example: Basic Setup
// graphql-codegen reads schema.graphql, generates matching TS types.
// codegen.yml: { generates: { "types.ts": { plugins: ["typescript"] } } }
console.log("Code generation keeps resolver types in sync with the schema");
Typed Example
A typed example: a schema field user(id: ID!): User generates a resolver signature (parent, args: { id: string }, context) => Promise<User>, so returning an object missing a required User field is flagged immediately.
Example: Typed Example
interface User { id: string; name: string; }
interface QueryArgs { id: string; }
async function userResolver(parent: unknown, args: QueryArgs): Promise<User> {
return { id: args.id, name: "Ravi" };
}
userResolver(null, { id: "1" }).then(console.log);
Project Usage
In a real project, regenerating types as part of the build (whenever the schema changes) keeps resolvers from silently drifting out of sync with the schema they're supposed to implement.
Example: Project Usage
// package.json: "build": "graphql-codegen && tsc"
console.log("Regenerating types on every schema change keeps resolvers honest");
Best Practices
Run code generation as an automated build/CI step rather than a manual one-off command, since a schema change that isn't followed by regeneration will leave stale, misleading types in the codebase.
Example: Best Practices
// CI step: npx graphql-codegen --check
console.log("Run codegen in CI, not just manually, to avoid stale types");
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first:
- Todo App with TypeScript
- REST API with Express + TypeScript
- React Dashboard with TypeScript
- CLI Tool with TypeScript
- Library with TypeScript
- Full Stack TypeScript App
- TypeScript Design System
- TypeScript Monorepo Project
- Authentication System
- Real-time App with Socket.io
- GraphQL API with TypeScript
- Microservices with TypeScript
- TypeScript Best Practices Review
- What to Learn Next