What is @graphql-codegen/typescript?
The @graphql-codegen/typescript package is a powerful tool designed for generating TypeScript typings directly from GraphQL schemas and operations. It automates the process of creating type definitions, making it easier to work with GraphQL in TypeScript projects by ensuring type safety and reducing the manual effort required to keep types in sync with the GraphQL schema.
Generating TypeScript Types from a GraphQL Schema
This feature allows you to generate TypeScript interfaces and types from a GraphQL schema. The code sample demonstrates how to programmatically generate TypeScript types using the GraphQL Code Generator CLI.
const { generate } = require('@graphql-codegen/cli');
async function generateTypes() {
const output = await generate(
{
schema: './schema.graphql',
generates: {
'./types.ts': {
plugins: ['typescript']
}
}
},
true
);
}
generateTypes();
Generating TypeScript Operations (Queries, Mutations, Subscriptions)
This feature generates TypeScript types for GraphQL operations, such as queries, mutations, and subscriptions. The code sample shows how to generate types for operations, enhancing type safety and development experience in TypeScript projects.
const { generate } = require('@graphql-codegen/cli');
async function generateOperations() {
const output = await generate(
{
schema: './schema.graphql',
documents: './src/**/*.graphql',
generates: {
'./graphql.ts': {
plugins: ['typescript', 'typescript-operations']
}
}
},
true
);
}
generateOperations();