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
Approach 1: Using typeof Operator
You can use the typeof
operator to get the type of a variable at runtime. It returns a string representing the type of the operated variable.
Example: In this example, we are using typeof Operator to get the type of a variable.
let myVar: number = 42; console.log( typeof myVar);
|
Output:
number
Approach 2: Using instanceof Operator
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.
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
Approach 3: Using Type Guards
You can create custom type guards using functions that narrow down the type of a variable based on certain conditions.
Example: In this example, we are using Type Guards to get the type of a variable.
function isString(value: any): void {
if ( typeof value === "string" ) {
console.log( "It's a string!" );
}
else {
console.log(`Passed value is
of ${ typeof age}
type.`)
}
} let greet: any = "Hello, TypeScript!" ;
const age: any = 20; isString(greet); isString(age); |
Output:
It's a string!
Passed value is of number type.