2.5 Type guards

The TypeScript type inference system looks for some conditional statements and operators to identify the type of a variable.

Getting Ready

All you need to be able to use types guards is an installation of TypeScript version 2.0 or higher.

How to do it…

A type guard is just a conditional block which uses the instanceof or typeof operators:

const x: any = {};
if(typeof x === "string") { 
  x.splice(1,1); //
x.foo(); // no errors as the type of x is any here

How it works…

The TypeScript compiler is able to identify when we use the typeof or the instanceof operators and throws an error as the type of x is string inside the conditional block (type guard).

There’s more…

TypeScript 2.0 or higher also introduces the possibility of creating our own type guards:

function isCat(a: Animal): a is Cat {
  return a.name === 'kitty';

As we can observe in the preceding code snippet a user defined type guard is just a function which performance a type assertion and returns a boolean value. The only difference with a normal function is that in this case the return type is not the boolean type and a special syntax is used instead.

The syntax is based on the syntax used in the declaration of generic constraint (we will learn more about it later in this chapter) but all you need to know for now is that you need to mention the name of the variable that is involved in the type assertion, the reserved keyword “is” and the “type” used in the assertion. Once we have defined our custom type guard we can apply then just like when we applied the typeof and instanceof type guards:

const x: Animal;
if(isCat(x)) {
  x.meow(); // x is Cat in this block

Source Code

Type guards

Shiv Kushwaha