How to get a variable type in Typescript?
I have a variable.
abc:number|string;
How can I check its type? I want to do something like below:
if (abc.type === "number") {
// do something
}
For :
abc:number|string;
Use the JavaScript operator typeof
:
if (typeof abc === "number") {
// do something
}
TypeScript understands typeof
🌹
This is called a typeguard.
More
For classes you would use instanceof
e.g.
class Foo {}
class Bar {}
// Later
if (fooOrBar instanceof Foo){
// TypeScript now knows that `fooOrBar` is `Foo`
}
There are also other type guards e.g. in
etc https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html
I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof
if(task.id instanceof UUID) {
//foo
}
The other answers are right, but when you're dealing with interfaces you cannot use typeof or instanceof because interfaces don't get compiled to javascript.
Instead you can use a typecast + function check typeguard to check your variable:
interface Car {
drive(): void;
honkTheHorn(): void;
}
interface Bike {
drive(): void;
ringTheBell(): void;
}
function start(vehicle: Bike | Car ) {
vehicle.drive();
// typecast and check if the function exists
if ((<Bike>vehicle).ringTheBell) {
const bike = (<Bike>vehicle);
bike.ringTheBell();
} else {
const car = (<Car>vehicle);
car.honkTheHorn();
}
}
And this is the compiled JavaScript in ES2017:
function start(vehicle) {
vehicle.drive();
if (vehicle.ringTheBell) {
const bike = vehicle;
bike.ringTheBell();
}
else {
const car = vehicle;
car.honkTheHorn();
}
}