How to check the type of a variable or constant in TypeScript?

November 10, 2021 - 2 min read

To check the type of a variable or a constant, you can use the typeof operator followed by the variable name in TypeScript. This is the same method used in the case of vanilla JavaScript code.

For example, let's say we have a variable called name with the value of John Doe like this,

// a simple variable
let name = "John Doe";

Now to check if the type of the name variable is a string, we can use an if conditional statement and use the typeof operator to check if the name variable's type matches with string.

It can be done like this,

// a simple variable
let name = "John Doe";

// check if the "name" variable type is of "string"
if (typeof name === "string") {
  console.log("It is of 'string' type");
} else {
  console.log("It is not of 'string' type");
}

/* OUTPUT: */

// It is of 'string' type

Just like we checked for the string type using the typeof operator, we can also check for the following types too in TypeScript:

  • number
  • bigint
  • boolean
  • symbol
  • undefined
  • object
  • function

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.