Categories
TypeScript Answers

How to get a variable type in TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *