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.
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
Contact Us