Open In App

TypeScript Instanceof Operator

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
4 Likes
Like
Report

The TypeScript instanceof operator checks if an object is an instance of a specified class or constructor function at runtime. It returns a boolean value: `true` if the object is an instance of the type, and `false` otherwise, ensuring robust type checking during execution.

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: Using instanceof with TypeScript Classes

This example demonstrates the basic usage of the instanceof operator with TypeScript classes.

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: Using instanceof with TypeScript Constructor Functions

This example demonstrates the usage of the instanceof operator with constructor functions in TypeScript.

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

The instanceof operator is a powerful tool in TypeScript for type checking at runtime. It allows you to verify if an object is an instance of a specific class or constructor function, which can be useful in various scenarios such as type assertions and debugging. By understanding and using instanceof, you can ensure more robust type safety in your TypeScript applications.


Next Article

Similar Reads