TypeScript : Type guards

Alaa Chakroun
eDonec
Published in
3 min readMay 20, 2021

Type gatekeeping is not that bad.

Photo by photorbi on Unsplash

Ever wondered why, sometimes, does a simple task need to be unnecessarily complicated and convoluted to achieve, and that feeling of self doubt and the “I am definitely doing this the wrong way” vibe you get while progressing ?

I definitely did, and in this article, I am trying to show to do things the right way around in the first place, so let’s get it started.

What are Type guards ?

While working in JavaScript, many of us wrote some code that resembles the following.

This is the correct way of dealing with JavaScript primitives and classes. But in TypeScript, we often deal with union or unknown types, so writing conditional code depending on the input’s type might become tricky and introduces some code smell.

It’s clear that we are failing to communicate to TypeScript that we are trying to narrow down a union type, and this is where we get introduced to type guards.

Type guards are regular functions that return a boolean, but have the unique property of assuring that depending on the returned boolean, the value tested is of a set type. This may either sound really simple or really convoluted so nothing beats diving in the code to try it out ourselves.

How to use Type guards ?

Let’s say that in this case, we are going to write a Type guard that checks if the input is of type Pet or not. So we can write the following function.

This function looks like it does the same thing as our last failed type assertion condition so what makes it different ? It’s none other than the return type.

We communicated to the TypeScript compiler that if the result of this function is truthy, then the input argument is of type Pet. So we can easily write our conditions using the result of this Type guard.

This results on less messy, more maintainable and readable code and that’s something that we all can appreciate.

Final words

Type guards are yet another tool provided by TypeScript to provide a more type-strict development environment and that enables us to be more confident when writing applications and maintaining them.

This has been developed by myself at eDonec.

--

--