Typescript conditionals

Matheus Vellone
2 min readJul 27, 2023

--

Imagine you have a function that receives a query name and a input and of course, returns an output. How do we make it 100% type safe?

The most basic way is to type it like this

See this code in TS Playground here

But there are some problems:

  1. queryName might have a typo, or the developer might not know all possible query names
  2. queryInput isn’t typed in any form and accepts anything
  3. the return type of the runQuery would be any, and it’s usage can be dangerous, possibly leading to runtime errors

Let’s make this function type safe!

First we need to type all query names and restrict our queryName parameter as a valid QueryName

See this example in TS Playground here

But this covers only the queryName and we still have any in the input and output.

Now lets move on into the fun part: typing the input and output.

Also available in TS Playground here

With this, we now can type each query individually in both their inputs and outputs.

I actually use this for some 20+ queries in a small project and it works perfectly.

This is also a great way to type external APIs. You can have a queryExternalAPI(method, url, body) function and type it accordingly to the providers documentation.

Typing dynamically is very powerful to keep the implementation generic enough to be reusable while also having type safety to avoid runtime errors.

This is even better with strict typings as I write in this article: Using phantom types to extreme type guard

--

--

No responses yet