How to useinstanceof Operator in Typescript
The instanceof
operator checks if an object is an instance of a particular class or type. It can be used to check the type of an object.
Example: In this example, we are using instanceof Operator to get the type of a variable.
Javascript
class MyClass { // class definition } let myInstance = new MyClass(); if (myInstance instanceof MyClass){ console.log(`myInstance is an instance of class MyClass and its type is: ${ typeof myInstance}`) } |
Output:
myInstance is an instance of class MyClass and its type is: object
How to Get a Variable Type in TypeScript ?
To get a variable type in TypeScript, we have different approaches. In this article, we are going to learn how to get a variable type in Typescript.
Below are the approaches used to get a variable type in TypeScript:
Table of Content
- Using typeof Operator
- Using instanceof Operator
- Using Type Guards
Contact Us