A Look at the instanceof Type Guard in TypeScript

Alfred M. Adjei

The instanceof operator is used to determine whether or not a type is of a particular constructor function. For example, since an interface can be implemented by several classes, how do we determine which class initializes a particular variable if it’s declared which an interface type? We can achieve that using the instanceof operator.

Let’s look at an example:

interface Person {
  id();
}


class Chef implements Person {
  id() {
    console.log("I am a chef")
  }
  cook(){
    console.log("I love to cook");
  }
}


class Driver implements Person {
  id() {
    console.log("I am a driver")
  }

  drive() {
    console.log("I love to drive");
  }
}


let person: Person;

In the code example above, we have two classes, Chef and Driver which both implement the Person interface. Both classes also have an extra method, which is cook() and drive() respectively.

🐊 Alligator.io recommends

Our recommended TypeScript courses

The person variable declared beneath has a type of Person, which means it can be initialized with either the Driver or Chef class. So how will we know which class initializes it? Yes, you guessed right! By using instanceof. Let’s create a function called init which acts differently depending on the instance passed into it.

function init(obj: Person) {
  if(obj instanceof Chef) {
    obj.cook();
  }

  if(obj instanceof Driver) {
    obj.drive();
  }
}

By using the instanceof operator, IntelliSense rightly provides us with methods only for the Chef in the first if block and methods only for Driver in the second if block.

chef methods

driver methods

When the obj passed-in is an instance of Chef, we call it’s cook() method and when it’s Driver, we call it’s drive() method.

person = new Chef();
init(person); // I love to cook

person = new Driver();
init(person); // I love to drive

Difference Between the instanceof & typeof Operators

If you read the previous post on typeof, you may be wondering what the difference is between instanceof and typeof. Below are two main differences.

  • 1: typeof returns a type and instanceof returns a boolean

Using our person variable from above, let’s see an example

person = new Chef();

console.log(typeof person) // object (a type)
console.log(person instanceof Chef) // true (a boolean)
  • 2: typeof takes only the name of the variable for which we are checking it’s type on it’s right-hand and nothing on the left. instanceof takes the name of the variable on it’s left-hand and the name of the function or class on the left.
  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#