Hello Friends 👋,
Welcome To Infinitbility! ❤️
Same like javascript, TypeScript have typeof Operator to check datatype of variable. using typeof
we are able to check any variable type and compare with our own condition.
Let start today tutorial How to check type of variable in typescript?
TypeScript provide typeguard and typeof
one of them. we will all of them but in this tutorial we will focus on typeof
.
typeof example
let str: string = "01234";
console.log(typeof str);
if(typeof str == 'string'){
console.log("str is string");
}
Output
Handle multiple probabilities of data type
let str: string | number;
str = 123;
console.log(typeof str);
if(typeof str == 'number'){
console.log("str is number");
}