Typescript conditionals
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
But there are some problems:
queryName
might have a typo, or the developer might not know all possible query namesqueryInput
isn’t typed in any form and accepts anything- the return type of the
runQuery
would beany
, 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
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.
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