...

/

The instanceof Operator

The instanceof Operator

Learn how to use the instanceof operator in TypeScript to test object inheritance and determine class instances.

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:

// 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 ...