Open In App

TypeScript Instanceof Operator

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The instanceof is a TypeScript operator that can check whether an object belongs to a particular class or type of the passed object at the run time. It always returns a boolean value based on the condition check.

Syntax:

objectName instanceof typeEntity

Parameters:

  • objectName: It is the object whose type will be checked at the run time.
  • typeEntity: It is the type for which the object is checked.

Return Value:

It returns true if the object is an instance of the passed type entity. Otherwise, it will return true.

Example 1: The below example will show you a basic usage of the instanceof operator with TypeScript classes.

Javascript
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

const person1 = new Person("Pankaj", 20);
console.log(person1 instanceof Person);

const randomObject: { name: string, job: string } =
    { name: "Neeraj", job: "Developer" };
console.log(randomObject instanceof Person);

Output:

true
false

Example 2: The below example will show you a basic usage of the instanceof operator with TypeScript constructor functions.

Javascript
function Company
    (name: string, est: number) {
    this.name = name;
    this.est = est;
}

const GFG =
    new Company("GeeksforGeeks", 2009);
const cmpny2 = {
    name: "Company2",
    est: 2010
}
console.log(GFG instanceof Company);
console.log(cmpny2 instanceof Company);

Output:

true
false

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads