Learn TypeScript

Using an `instanceof` type guard

Using an `instanceof` type guard

In this lesson, we will learn about the instanceof operator and how it can be used to narrow the type of class objects.

Understanding the instanceof operator

instanceof is a JavaScript operator that can check whether an object belongs to a particular class. It also takes inheritance into account.

The syntax is:

objectVariable instanceof ClassName;

The expression returns true or false depending on whether the object belongs to the class or not.

The TypeScript compiler uses an instanceof expression to narrow the variable's type in the expression.

An example

We are going to explore the instanceof type guard in the code editor below:

TypeScriptOpen exercise in CodeSandbox

The code contains a Contact base class and two classes that are derived from it. The code also contains a sayHello function that we will finish implementing.

  • In the function, output "Hello {firstName}" if the contact parameter belongs to the Person class:
function sayHello(contact: Contact) {
if (contact instanceof Person) {
console.log("Hello " + contact.firstName);
}
}
🤔

What is the type of contact in the if branch?

  • Complete the function implementation by outputing "Hello {name}" if the contact parameter is belongs to the Organisation class.
🤔

What is the type of contact in the if branch you just implemented?

Neat!

Summary

The instanceof operator can be used to help TypeScript narrow the type of a class object variable. It only works on class structures and not other TypeScript structures, such as interfaces.

Next up, we will learn a more general type guard for use on object structures.

© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more