Guide: TypeScript-only for front-end
Even while using another GraphQL Client (not listed in our guides) or willing only to use generated TypeScript types, GraphQL Code Generator still got you covered!
@graphql-codegen/typescript-operations
is the perfect plugin if you prefer only manipulating generated TypeScript types.
Given the following example:
import gql from 'graphql-tag'
const postsQueryDocument = gql`
query Posts {
posts {
id
title
author {
id
firstName
lastName
}
}
}
`
const Posts = () => {
const { data } = useCustomFetchGraphQLData(postsQueryDocument)
}
Using @graphql-codegen/typescript-operations
would generate the TypeScript type definitions for only used Query, Mutation, Subscription and Fragment.
Just a few configuration steps are required to get those TypeScript types generated:
Install
yarn add -D @graphql-codegen/typescript-operations @graphql-codegen/typescript
Configure the plugin
Create or update your codegen.yaml
file as follows:
schema: http://my-graphql-api.com/graphql
documents: './src/**/*.tsx'
generates:
graphql/generated.ts:
plugins:
- typescript
- typescript-operations
schema
and documents
values
schema
needs to be your target GraphQL API URL ("/graphql"
included).
documents
is a glob expression to your .graphql
, .ts
or .tsx
files.
Run the codegen and update your code
Assuming that, as recommended, your package.json
has the following script:
{
"scripts": {
"generate": "graphql-codegen"
}
}
Running the following generates the graphql/generated.tsx
file.
yarn generate
We can now use the generated types as follows:
import gql from 'graphql-tag'
import { PostsQuery } from '../graphql/generated.tsx'
const postsQueryDocument = gql`
query {
posts {
id
title
author {
id
firstName
lastName
}
}
}
`
const Posts = () => {
const { data } = useCustomFetchGraphQLData(postsQueryDocument)
const result = data as PostsQuery
}
For more information on the @graphql-codegen/typescript-operations
plugin configuration, please refer to its documentation.