Search⌘ K
AI Features

The instanceof Operator

Explore how to use the instanceof operator to verify whether objects belong to specific classes or inherit from them within TypeScript. Understand how this operator works with class hierarchies including direct and indirect inheritance, helping you manage and test object relationships accurately.

We'll cover the following...

Introduction to the instanceof operator

JavaScript provides the instanceof operator to test whether the given function name appears in the prototype of an object.

In TypeScript terms, the use of this keyword allows us to detect whether an object is an instance of a class or whether it has been derived from a particular class.

This is best illustrated with an example as follows:

TypeScript 4.9.5
// Definition of Class A
class A {}
// Definition of Class BfromA that extends Class A
class BfromA extends A {}
// Definition of Class CfromA that extends Class A
class CfromA {}
// Definition of Class DfromC that extends Class CfromA
class DfromC extends CfromA {}
Class hierarchy
  • We define four classes in a class hierarchy, starting with a simple class named A on line 2.

  • We then define ...