DevToolBoxGRATIS
Blog

Generación de tipos GraphQL: Automatiza tus tipos TypeScript

12 min de lecturapor DevToolBox

Manually writing TypeScript types for your GraphQL API is a recipe for type drift, runtime errors, and wasted developer time. Type generation automates this entirely, keeping your frontend types perfectly in sync with your API schema.

Convert GraphQL schemas to TypeScript types instantly →

1. Why Type Generation Matters

GraphQL APIs are strongly typed by design — the schema defines every query, mutation, field, and argument. But without type generation, frontend developers manually duplicate these types in TypeScript, creating two sources of truth that inevitably diverge.

Without type generation: You write TypeScript interfaces by hand, hope they match the schema, and discover mismatches as runtime errors in production. When the API adds a field, your types are stale.

With type generation: Types are generated automatically from the schema. When the API changes, you regenerate types and the TypeScript compiler tells you exactly what frontend code needs updating. Zero guesswork.

Type generation typically saves 2–5 hours per week on medium-sized projects and eliminates an entire category of bugs.

2. Manual vs Automated Approaches

Here's a comparison of the two approaches:

AspectManualAutomated
AccuracyError-proneAlways matches schema
MaintenanceManual updates neededOne command to sync
Setup CostNone~15 min one-time setup
Ongoing CostHours per weekNear zero
Schema Drift DetectionAt runtime (production)At compile time (CI)

The only valid reason for manual types is when you're consuming a small, rarely-changing API and don't want to add tooling. For everything else, automate.

3. GraphQL SDL Basics

The Schema Definition Language (SDL) is how GraphQL schemas are written. Understanding SDL is essential for working with type generators:

type User {
  id: ID!
  name: String!
  email: String!
  age: Int
  posts: [Post!]!
  role: Role!
}

type Post {
  id: ID!
  title: String!
  content: String
  author: User!
  tags: [String!]
  createdAt: DateTime!
}

enum Role {
  ADMIN
  EDITOR
  VIEWER
}

input CreateUserInput {
  name: String!
  email: String!
  age: Int
  role: Role = VIEWER
}

SDL supports these key constructs: type (object types), input (input objects), enum (enumeration types), interface (abstract types), union (union types), and scalar (custom scalar types).

The exclamation mark (!) means non-nullable. Without it, fields default to nullable — the opposite of most programming languages.

4. Type Mapping Rules

Type generators follow consistent rules to map GraphQL types to TypeScript:

GraphQLTypeScriptNotes
String!stringNon-nullable string
Stringstring | nullNullable string
Int! / Float!numberJS has one number type
Boolean!booleanDirect mapping
ID!stringIDs are serialized as strings
[String!]!string[]Non-null array of non-null strings
[String](string | null)[] | nullNullable array of nullable strings
enum Roleenum RoleTS enum or string union

Understanding these mappings helps you predict and validate generated output, and write better GraphQL schemas that produce cleaner TypeScript types.

5. Code Generators

Several tools can generate TypeScript types from GraphQL schemas. The most popular:

GraphQL Code Generator (@graphql-codegen) is the industry standard. It's plugin-based and supports not just types, but also typed hooks for React Query, Apollo, and urql:

# codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: './schema.graphql',        // or a URL
  documents: 'src/**/*.graphql',     // your queries/mutations
  generates: {
    'src/generated/graphql.ts': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typescript-react-query',    // optional: typed hooks
      ],
    },
  },
};

export default config;

Alternative generators:

  • gql.tada — Compile-time type inference without code generation, uses TypeScript template literal types
  • Pothos — Code-first schema builder that derives types from your resolver code
  • genql — Generates a fully typed SDK client from any GraphQL endpoint

6. Integration Workflow

A typical type generation workflow integrates into your development and CI/CD pipeline:

  1. Development: Run codegen in watch mode (--watch) alongside your dev server. Types update automatically as you edit .graphql files
  2. Pre-commit: Add codegen to a pre-commit hook to ensure generated types are always committed
  3. CI/CD: Run codegen and tsc --noEmit in CI to catch schema drift before deployment
  4. Schema updates: When the backend updates the schema, regenerate types and fix any TypeScript errors before merging

Recommended package.json scripts:

{
  "scripts": {
    "codegen": "graphql-codegen",
    "codegen:watch": "graphql-codegen --watch",
    "typecheck": "tsc --noEmit",
    "precommit": "npm run codegen && npm run typecheck"
  }
}

Keep generated files in version control. This makes PRs clearly show what schema changes affect, and lets developers work without running codegen locally.

7. Tool Recommendation: GraphQL to TypeScript

Need to quickly convert a GraphQL schema to TypeScript types without setting up a full codegen pipeline? Our GraphQL to TypeScript converter handles it in seconds:

  • Converts GraphQL object types to TypeScript interfaces
  • Maps enums, input types, and union types correctly
  • Handles nullable vs non-nullable fields
  • Supports nested and recursive type definitions

Paste your GraphQL SDL and get clean TypeScript types instantly. Perfect for quick prototyping, learning, and one-off conversions.

Convert GraphQL schemas to TypeScript types instantly →

Frequently Asked Questions

Should I use code generation or gql.tada for type safety?

For most teams, GraphQL Code Generator is the safer choice — it has wider ecosystem support, works with any client library, and produces standard TypeScript files. gql.tada is innovative but requires TypeScript 5.0+ and has a steeper learning curve. Choose gql.tada if you want zero-config type safety and your team is comfortable with advanced TypeScript.

How often should I regenerate types?

In development, use watch mode for instant regeneration. In CI, run codegen on every push. The key rule: never manually edit generated files. If you need custom types, create a separate file that imports and extends the generated types.

Can I generate types from a remote GraphQL endpoint?

Yes. Most code generators support introspection — they can query a running GraphQL server for its schema and generate types from that. Configure the endpoint URL in your codegen config. For production APIs, you can also export the schema as an SDL file and use that as the source.

𝕏 Twitterin LinkedIn
¿Fue útil?

Mantente actualizado

Recibe consejos de desarrollo y nuevas herramientas.

Sin spam. Cancela cuando quieras.

Prueba estas herramientas relacionadas

GTGraphQL to TypeScriptGQLJSON to GraphQLTSJSON to TypeScript

Artículos relacionados

JSON a TypeScript: Guia completa con ejemplos

Aprende a convertir datos JSON a interfaces TypeScript automáticamente. Objetos anidados, arrays, campos opcionales y mejores prácticas.

REST API Mejores Prácticas: La guía completa para 2026

Aprende las mejores prácticas de diseño REST API: convenciones de nombres, manejo de errores, autenticación y seguridad.

GraphQL a TypeScript: Guia de generacion de codigo

Genere tipos TypeScript desde schemas GraphQL.