How to useType Guards in Typescript
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.
Javascript
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.
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