How to Check Variable Types in TypeScript

Ferenc Almasi • 2022 September 19 • 📖 3 min read

To check variable types in TypeScript, use the typeof operator which returns the type of a variable as a string. Take the following code as an example:

const variable1: string | number = '42'
const variable2: string | number = 42

// This will return "string"
console.log(typeof variable1)

// This will return "number"
console.log(typeof variable2)

// This is called typeguard
if (typeof variable1 === 'string') {
    variable1.toLowerCase()
}
Copied to clipboard!

Using a type check to execute code is called a typeguard, and can ensure that you work with the correct type. For example, we don't have a toLowerCase method on numbers, but we have it for strings. The typeof operator can have the following return values:

typeof '1'       // Returns "string"
typeof 1         // Returns "number"
typeof NaN       // Returns "number"
typeof true      // Returns "boolean"
typeof undefined // Returns "undefined"
typeof Symbol()  // Returns "symbol"
typeof []        // Returns "object"
typeof null      // Returns "object"
Copied to clipboard!

If you are interested in why null would be an object type, I recommend checking out "The history of typeof null" by 2ality. Another interesting behavior is that if you use the typeof operator twice after each other, you will always get a "string" type.

typeof typeof 1    // Returns "string"
typeof typeof true // Returns "string"
typeof typeof []   // Returns "string"
typeof typeof null // Returns "string"
Copied to clipboard!

We can also use the typeof operator to dynamically assign the type for other variables. This can be done in the following way:

// Assigning type to a variable using the typeof operator
const variable1: string = 'string'
const variable2: typeof variable1 = 42 // This will throw an error: "Type 'number' is not assignable to type 'string'"
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Using instanceof

It's also worth noting that if you need to check whether your variable is a type of a class, you need to use the instanceof keyword instead of the typeof operator.

class Fruit {}

const fruit = new Fruit()

// This will return true
if (fruit instanceof Fruit) {
    // Call method only available on Fruit classes
    fruit.grow()
}
Copied to clipboard!

Since the fruit variable was created as a new instance of the Fruit class, the if statement will be evaluated to true.

Using the instanceof operator will always return a boolean value (true or false). 

Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended