Automagically Typed GraphQL Queries and Results With Apollo

Csaba Apagyi
Geek Culture
Published in
2 min readMay 4, 2021

Enjoy writing GraphQL queries as strings and getting untyped results? Me neither. The issue is sometimes called the “double declaration problem” and you can read more about it in more detail here and here, but you get the idea. Can’t you just take GraphQL schema, write typed queries, and get typed results? How about out of the box, without having to explicitly name the types?

TLDR; You can do all those things with a single method! In the nestjs-starter repo, I’m using GraphQL with end-to-end typing to connect NestJS and Next.js.

There are an overwhelming amount of attempts to solve this issue, most notably:

  • apollo’s codegen (1, 2, 3) - a partial solution for typing results that still requires you to explicitly assign types
  • an experimental babel plugin (!) - certainly feels like an overkill
  • several libraries solving one part or the other: gotql, typed-graphqlify, graphql-typed-client
  • gqless, a client based on a different paradigm that requires code and concept changes (but seems really cool if you can adopt it)
  • some ideas for the apollo client (1, 2)
  • (I suspect the executable schema implementation could be reused somehow but no one seems to do that?)

All of the above are partial solutions or not something you can just drop in and use with apollo.

graphql-zeus to the rescue!

Last updated: 2022.03 (graphql-zeus 4.0.4)

Step 1, Install

Step 2, Generate types

You can choose to commit the generated file or gitignore it and include the generation in your build script.

Step 3, Typed client

The — apollo flag generates a typed version of Apollo’s useQuery called useTypedQuery that you can use right away. It takes a typed query and returns typed results.

Sometimes you can’t use hooks (such as in Next.js SSR). For these cases, you can define a typedQuery similar to useTypedQuery

You can see this used in practice in the nestjs-starter repo, for example on the orders page.

The repo showcases an example NestJS MVC architecture made for quick prototyping. It natively serves Next.js as frontend, connected with GraphQL, and some added functionality such as authentication via Passport and Cognito.

--

--