Generate TypeScript Types from GraphQL Schema using Apollo CLI

Ashok Vishwakarma
2 min readJan 10, 2021

--

GraphQL is cool and it helps frontend and backend both, I have been using it for a quite a while and one thing always bothers me a lot while using TypeScript in the FrontEnd.

The schema defined in GraphQL are well-typed and can be used in TypeScript client to type our GraphQL queries, mutations and responses but it's written in String and there isn't a direct way of using it.

So after researching a bit and getting deep into the Apollo documentation I have discovered Apollo has a CLI which we can use in a variety of ways on of them downloading the whole schema in a JSON format using below command

apollo client:download-schema <path-to-save>

What this means is we can use this command to download the schema in JSON format and the parse to convert the GraphQL schema into TypeScript interfaces or types.

Setting up the npm script

To setup, I have created a npm script named download:schema in my package.json file to download the schema from the Apollo Server into the root of my project with the filename schema.json

"download:schema": "apollo client:download-schema schema.json"

And one another npm script generate:types which simply runs the apollo-types.js file from the root of my project.

"generate:types": "node apollo-types.js"

Reading the schema.json

A typical schema.json from Apollo server look like this

{
"__schema": {
"queryType": {
"name": "Query"
},
"mutationType: {
"name": "Mutation"
},
"subscriptionType": {
"name": "Subscription"
},
"types": [
{
"kind": "OBJECT",
"name": "Query",
"description": null,
"args": [...]
}
],
"directives": [...],
}
}

We can simply read the JSON file to extract all the types and by using its properties we can convert the same into TypeScript types or interfaces.

Check out the full code below

After saving the graphql.types.ts in the project, we can simply use it anywhere as required.

import { Response, UserResult } from 'graphql.types';

Let me know your thoughts and if there is any other way you have implemented something similar.

--

--

Ashok Vishwakarma
Ashok Vishwakarma

Written by Ashok Vishwakarma

@GoogleDevExpert — #WebTechnologies & @angular | #Principal #Architect at @Naukri | #Entrepreneur | #TechEnthusiast | #Speaker

No responses yet