DEV Community

Cover image for Centralizing type checking with Type Guards
Nícolas Gabriel
Nícolas Gabriel

Posted on

Centralizing type checking with Type Guards

Hello my fellow TypeScript developer!

Introduction

Have you ever tried accessing properties on a variable in TypeScript, only to find that TypeScript isn’t sure what type it is? You know it could be one of two things, but TypeScript’s autocompletion is only showing you common properties?

Let’s say you have an Animal type, which can either be a Bird or a Dog. You need to figure out whether the animal you’re working with is a bird before performing bird-specific logic.

Type animal has two types, and we need to check first which one it is

In this situation, it would be easy to fix this problem, to know if the animal provided is a bird or not, we would only need to check its name (or some sort of identifier).

Showing animal can be a Bird after checking name

This works because TypeScript can infer that the animal is a Bird by the return of our function, and therefore provides the correct type information. But it is not ideal, doesn't follow well DRY principles... For example if we need to do the same check in another place we would need to do the same animal.name === "bird" again...

And if someday we end up changing "bird" to "eagle", every file with this check would need to be updated. So how could we center the logic in order to be easier to maintain and re-use?

Simple! We can create a Type Guard, which is a function that is able to assert that a variable is from a specific type, making the process of checking types easier and centered in one place.

Creating a Type Guard

In practice, a Type Guard is a function that returns a boolean, and this boolean is the assertion if a variable is or not from a specific type.

If we want to create a Type Guard for the above scenario, it would be written this way:

Type guard to check bird
If it returns true then animal is a Bird, if it is false it is a Dog.

The important part here is the value is Type syntax, which is the core of a Type Guard. With it, we can use this function anywhere and our typings will be more powerful.

Using the Type Guard

Let's try applying it to our previous example:

Using type guard

And as you can see, if it is true it enters the if statement, which has the correct type for Animal: Bird. TypeScript is able to assume that because of our type-guard :).

And TypeScript is smart, so if we add an else, then it would be considered a Dog on it!

A good detail is that the value is Type syntax can be used in any function, even in callbacks! So for example you can also use it on a find, every, a filter or anywhere you think it would be helpful.

Conclusion

I hope I helped you learn something new today! If you still have any questions, feel free to comment them below or connect to me in my social medias.

See you!

Top comments (0)