Why Convert GraphQL to TypeScript?
GraphQL APIs are self-documenting through their schema, but that schema is GraphQL SDL — not TypeScript. Without code generation, you're manually maintaining TypeScript types that mirror your GraphQL schema, which inevitably drifts out of sync. Generating TypeScript types from your GraphQL schema gives you compile-time safety for every query and mutation.
Quick Conversion: Online Tool
For prototyping or one-off conversions, use our GraphQL to TypeScript converter. Paste your schema SDL and get the equivalent TypeScript interfaces and enums instantly — no setup required.
GraphQL to TypeScript Type Mapping
Understanding the mapping between GraphQL and TypeScript is essential:
// GraphQL schema
type User {
id: ID! # → id: string
name: String! # → name: string
email: String # → email: string | null
age: Int # → age: number | null
posts: [Post!]! # → posts: Post[]
}
enum Role {
ADMIN # → ADMIN = "ADMIN"
USER # → USER = "USER"
}
input CreateUserInput {
name: String!
email: String!// Generated TypeScript
export enum Role {
ADMIN = "ADMIN",
USER = "USER",
}
export interface User {
id: string;
name: string;
email: string | null;
age: number | null;
posts: Post[];
}
export interface CreateUserInput {
name: string;
email: string;
}Using graphql-code-generator
For production projects, use graphql-code-generator to auto-generate types on every schema change:
npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescriptCreate codegen.ts:
import type { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
schema: 'https://your-api.com/graphql',
generates: {
'./src/generated/graphql.ts': {
plugins: ['typescript'],
config: {
avoidOptionals: false,
maybeValue: 'T | null',
},
},
},
};
export default config;Run generation:
npx graphql-code-generatorType-Safe Queries with graphql-request
Once you have generated types, use them with graphql-request or Apollo Client:
import { gql, request } from 'graphql-request';
import type { GetUserQuery, GetUserQueryVariables } from './generated/graphql';
const GET_USER = gql`
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;
const data = await request<GetUserQuery, GetUserQueryVariables>(
'https://api.example.com/graphql',
GET_USER,
{ id: '1' }
);Handling Nullable Fields Correctly
The biggest source of runtime errors when working with GraphQL in TypeScript is incorrect nullability. A GraphQL field without ! is nullable. Always treat these as T | null in TypeScript and add null guards:
const email = user.email; // string | null
if (email !== null) {
sendEmail(email); // email: string here
}
// Or with optional chaining
const domain = user.email?.split('@')[1]; // string | undefinedFor a quick comparison between manual and automated type generation approaches, see our GraphQL to TypeScript converter.
