Everything you might read below is basically included on this photo.

GraphQL + Typescript = strongly typed api schema

Adam Pietrasiak
Apr 20, 2018 · 2 min read

Instead of defining GraphQL schema and THEN resolvers code, let’s write both as one thing.

Let’s learn by example

We have Product entity written as TypeScript class with id and price fields. We also have computed field isExpensive that returns true if price > 50.

Le’ts define our first object type

Everything is strongly typed here. It’s important, as it will allow inferring GraphQL schema out of it.

Let’s move forward. Code above would give us fully functional GraphQL object type. Now let’s create schema that is using it.

Let’s add it to schema

We’ve added some root Query field called findProductById. It have some argument and it returns Product object defined previously.

Again everything (including arguments) is strongly-typed, so it’s possible to guess how GraphQL schema would look like and to generate it automatically.

Let’s generate such schema and start some Express GraphQL api server.

Let’s compile schema and create some graphql server

That’s all. Now, when we’d start server, it’ll handle query like:


As you’ve probably seen, I’m using library called typegql. It’s lib I’ve created with Prismake to help with 3 main things:

  • have graphql schema type-safe
  • have single source of truth for schema types (instead of separated graphql and resolvers definitions)
  • have types and business logic as close to each other as possible

You can check it out here.

More examples with typegql:

A to Z process of creating hello world api

Thanks for reading.

Follow me on twitter.

Check out typegql library.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade