添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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.

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:

false

Example 2: Using instanceof with TypeScript Constructor Functions

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

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:

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.

FAQs-TypeScript Instanceof Operator

When should you use the instanceof operator?

You should use the instanceof operator when you need to determine the specific class or constructor function an object instance belongs to, particularly in type checks and conditional logic.

Can instanceof be used with interfaces in TypeScript?

No, instanceof cannot be used with interfaces because interfaces do not exist at runtime. instanceof only works with classes and constructor functions that have runtime representations.

What types can be checked using the instanceof operator?

The instanceof operator can check objects against classes and constructor functions. It does not work with primitive types or interfaces.

How does instanceof differ from the typeof operator?

instanceof checks if an object is an instance of a class or constructor function, while typeof checks the type of a primitive value or the type of an object (e.g., “number”, “string”, “object”). typeof cannot distinguish between instances of different classes.

What are the limitations of the instanceof operator?

The instanceof operator only works with objects that have a valid prototype chain. It cannot be used to check primitive values or interfaces, and its functionality depends on the correct prototype linkage.

JavaScript Instanceof Operator
The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.  Syntax:let gfg = objectName instanceof objectTypeParameters: objectName: States the name of the Object.Return Value: This me
TypeScript instanceof narrowing Type
TypeScript instanceof operator is used for type narrowing, allowing us to check whether an object is an instance of a specific class or constructor function. When we use instanceof in a conditional statement, TypeScript narrows the type of a variable based on the result of the check. Syntax:if (objectToCheck instanceof ConstructorFunction) { // Cod
JavaScript TypeError - Invalid 'instanceof' operand 'x'
This JavaScript exception invalid 'instanceof' operand occurs if the right operand of the instanceof operator can not be used with a constructor object. It is an object that contains a prototype property and can be called. Message: TypeError: invalid 'instanceof' operand "x" (Firefox) TypeError: "x" is not a function (Firefox) TypeError: Right-hand
Difference Between instanceof and isPrototypeOf() in JavaScript
In JavaScript, understanding object relationships and type checks is crucial for the effective programming. The Two methods that facilitate these checks are instanceof and isPrototypeOf(). While both are used to the determine the type or prototype relationships in the JavaScript they operate differently and are suited for the different scenarios. T
Why we should prefer square operator over the dot operator to access the value from the object ?
The square notation should be used as much as possible as compared to the dot notation to access the value from the object in JavaScript. Let's first understand how to obtain the value by using the square notation and dot notation from the object. Square notation: In the square notation the keyName that is passed is treated as a variable and search
TypeScript in operator narrowing Type
In this article, we will learn about the 'in' operator narrowing Type in Typescript. In TypeScript, the 'in' operator is used to narrow or refine the type of an object within a conditional statement or block. It checks whether a specific property or key exists within an object, and if it does, it narrows the type of that object to include that prop
TypeScript Non-null Assertion Operator (Postfix !) Type
TypeScript non-null assertion operator (!) is used to assert that a value is non-null and non-undefined, even when TypeScript's strict null checks are enabled. This operator tells TypeScript to treat the expression as if it's guaranteed to have a value, eliminating compile-time null and undefined checks. Syntaxconst nonNullValue: Type = value!;Para
Difference Between Spread Operator and Array.concat() in Typescript
The spread operator and concat() method both are used to add elements to an array. But they are different from each other in many ways. Let us discuss the difference between both of them in detail. Spread OperatorThe spread operator creates a new array by merging the elements of the passed arrays or the values. It is denoted by three dots(...). It
What is the use of the in Operator in TypeScript ?
The in operator in TypeScript is used for checking whether a specified property exists in an object. It is a type-safe way to perform property existence checks, providing developers with a mechanism to ensure that certain properties are present before accessing or manipulating them. The primary use case for the in operator is within conditional sta
How to use Spread Operator in TypeScript ?
The spread operator in Typescript, denoted by three dots (`...`), is a powerful tool, that allows you to spread the elements of an array or objects into another array or objects. This operator makes it easy to copy arrays, combine arrays, or create shallow copies of iterable. Syntax...operatingValueExample 1: The below code implements the spread op
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not collected in the GeeksforGeeks mobile applications. Got It !
Please go through our recently updated Improvement Guidelines before submitting any improvements.
This improvement is locked by another user right now. You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.
You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!
Please go through our recently updated Improvement Guidelines before submitting any improvements.
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.