Sometimes, we want to get a variable type in TypeScript.
In this article, we’ll look at how to get a variable type in TypeScript.
How to get a variable type in TypeScript?
To get a variable type in TypeScript, we can use the typeof
or instanceof
operator.
For instance, we write
if (typeof abc === "number") {
// ...
}
if (fooOrBar instanceof Foo) {
// ...
}
to return the type of the abc
variable with typeof abc
.
And we use the instanceof
operator to check if fooOrBar
is created from the Foo
constructor.
Conclusion
To get a variable type in TypeScript, we can use the typeof
or instanceof
operator.