How to use the instanceof Operator In Typescript

This operator checks whether an object is an instance of a particular class or constructor. We can operate it by defining the testing object name before it and the class name after it.

Syntax:

objectName instanceof ClassName

Example: The below example illustrates the usage of the instanceof operator to check if an object is an instance of a class.

Javascript
class Person {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}

let person = new Person("John");
console.log(person instanceof Person);

Output:

true

How to Check the Type of an Object in Typescript ?

When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below.

Table of Content

  • Using the typeof Operator
  • Using the instanceof Operator
  • Using Type Guards

Similar Reads

Using the typeof Operator

This operator returns a string indicating the type of the operand. We can operate this with the objects to check their type in TypeScript....

Using the instanceof Operator

This operator checks whether an object is an instance of a particular class or constructor. We can operate it by defining the testing object name before it and the class name after it....

Using Type Guards

Type guards are functions that return a boolean indicating whether an object is of a specific type....

Contact Us