DEV Community

Cover image for Typescript : Type guards simply explained.
Ricardo Paul
Ricardo Paul

Posted on

Typescript : Type guards simply explained.

Today we're exploring a functionality in Typescript called type guards, if the name sounds strange to you,know however this is a technique that you probably have used in plain Javascript if you've been coding in that language for a while.

Type guards is a technique used in Typescript to get information about the type of a variable (to know what the type is) and this often happens within a conditional block like if/else. To achieve this, typescript makes use of some built-in javascript operators like typeof, instance of, the in operator which is used to determine if an object contains a property.

So this is enough theory already, let's go through some examples.
Oh just before, type guards mostly come to use when we're dealing with a function whose parameter has a union type as type annotation.
If you're not familiar with Union Types, you can take it literally as a union of types, e.g:
Type UnionOfTypes = string | number

Let's go through a failing code example to see where Type guards come in.

type StringOrNumber = string | number //our union type

function processAmount(amount: StringOrNumber){
    return amount + 10 //error
}
Enter fullscreen mode Exit fullscreen mode

In the snippet above, our function processAmount() takes an argument amount which can be either a string or a number.
In the function body, we just assume that amount is a number and try to add 10 to it. The compiler gets confused, it cannot add 10 (number) to
amount (string | number) and thus signals us that there's an error:
Operator '+' cannot be applied to types 'StringOrNumber' and 'number'

Ok, so what are we doing wrong? Well, we are not narrowing the type of the argument amount. We need a way to tell the compiler that it should treat
our variable as a number and let us perform our operation. That's where type guards come in.

type StringOrNumber = string | number

function processAmount(amount: StringOrNumber){
    if(typeof amount === "number"){
        return amount + 10
    }
    return amount
}
Enter fullscreen mode Exit fullscreen mode

This time, by using the typeof operator within a conditional block, we tell the typescript compiler to treat amount as a number within the scope and now our code can compile without errors.

That is Type guards in a nutshell, remember that there are other operators used to perform Type guards and narrowing in Typescript like instanceof and in. I'll cover these in a future blog post.

Top comments (0)