How to check type in typescript

How to check type in typescript

Last updated: Jan 23, 2023
Reading time · 4 min

banner

# Table of Contents

# Check the Type of a Variable in TypeScript

Use the typeof operator to check the type of a variable in TypeScript.

The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

Copied!
const myVar: string | number = 'bobbyhadz.com'; console.log(typeof myVar); // 👉️ "string" if (typeof myVar === 'string') console.log(myVar.toUpperCase()); // 👉️ "BOBBYHADZ.COM" >

We used the typeof operator to check the type of a variable in TypeScript.

The operator returns a string that indicates the type of the value and can be used as a type guard.

Copied!
const myVar: string | number = Math.random() > 0.5 ? 'Hello' : 1000; // 👉️ myVar has type string or number here if (typeof myVar === 'string') // 👇️ myVar has type string here console.log(myVar.toUpperCase()); > else // 👇️ myVar has type number here console.log(myVar.toFixed(2)); >

The variable is typed using a union and can have a type of string or number.

We can’t directly access string built-in methods on the variable because it might be a number.

The if statement checks if the type of the variable is a string, so TypeScript knows the variable stores a string in the if block.

The only other possible type the variable might store is a number , so the variable is typed as a number in the else block.

Here are some examples of using the typeof operator.

Copied!
console.log(typeof 'bobbyhadz.com'); // 👉️ "string" console.log(typeof 100); // 👉️ "number" console.log(typeof true); // 👉️ "boolean" console.log(typeof [1, 2, 3]); // 👉️ "object" console.log(typeof >); // 👉️ "object" console.log(typeof function example() >); // 👉️ "function" console.log(typeof NaN); // 👉️ "number" console.log(typeof undefined); // 👉️ "undefined" console.log(typeof null); // 👉️ "object" console.log(typeof class A >); // 👉️ "function"

Notice that using the typeof operator with an array returns object .

# Check the Type of a Variable using instanceof

If you need to check if a variable stores an instance of a specific class, use the instanceof operator.

Copied!
class Person > const person = new Person(); if (person instanceof Person) // 👇️ this runs console.log('value is an instance of Person'); >

The syntax for the instanceof operator is object instanceof constructor .

The operator returns true if the prototype property of the constructor appears anywhere in the prototype chain of the object.

The instanceof operator is very useful in TypeScript because it can be used as a type guard.

Copied!
class Person walk() console.log('person is walking'); > > class Animal run() console.log('animal is running'); > > function example(x: Person | Animal) // 👉️ x is type Person or Animal here if (x instanceof Person) // 👇️ x is type Person here x.walk(); > else // 👇️ x is type Animal here x.run(); > > const p1 = new Person(); const a1 = new Animal(); example(p1); // 👉️ "person is walking" example(a1); // 👉️ "animal is running"

The function takes a parameter of type Person or Animal , so before we access a class-specific method, we have to check an instance of which class was passed to the function.

# Using a type predicate to check the type of a variable

You can also use a type predicate to check the type of a variable.

Copied!
const person = name: 'Bobby Hadz', country: 'Chile', >; type Person = name: string; country: string; >; // 👇️ checks if obj has properties of Person function isPerson(obj: Person): obj is Person return 'name' in obj && 'country' in obj; > let bobby; if (isPerson(person)) // 👉️ person has type of Person here bobby = person; > else bobby = name: '', country: '' >; > console.log(bobby); // 👉️

The obj is Person syntax is a type predicate.

A predicate takes the form of parameter is Type , where parameter is the name of a parameter from the function signature.

In the example, we check if the passed-in value has the properties of an object of type Person .

If the condition is met, we return true from the isPerson function and the variable gets typed as Person .

# Checking if a variable stores an array

To check if a variable stores an array, use the Array.isArray() method.

Copied!
const arr: string[] = ['bobby', 'hadz', 'com']; console.log(Array.isArray(arr)); // 👉️ true

The Array.isArray() method returns true if the passed-in value is an array and false otherwise.

# Checking if a variable stores a NaN value

The type of NaN (not a number) is number . If you need to check if a specific value is NaN , use the Number.isNaN method.

Copied!
const example = Number('bobbyhadz.com'); console.log(example); // 👉️ NaN if (Number.isNaN(example)) console.log('Passed in value is NaN'); >

The Number.isNaN method will return true if the passed-in value has a type of number and is NaN .

# Checking if a variable stores null

The typeof operator returns «object» when you do typeof null .

Copied!
console.log(typeof null); // 👉️ "object"

If you are checking whether a variable stores a null value, don’t use the typeof operator, instead check directly.

Copied!
const example = null; if (example === null) console.log('Variable stores a null value'); >

# The typeof operator always returns a string

Note that the typeof operator always returns a string. A very common mistake is to do something like the following.

Copied!
const myVar = undefined; if (typeof myVar === undefined) console.log('myVar is undefined'); > else console.log('👉️ This block runs'); >

The else block in the example is run because we are checking if the type of myVar is equal to the value undefined .

This evaluates to false because typeof myVar returns a string of «undefined» and not the value undefined .

The typeof operator returns «function» for classes. This is because classes in JavaScript (and TypeScript) are just syntactic sugar for functions.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How To Check The Type In TypeScript?

Tim Mouskhelichvili

When developing TypeScript projects, developers often need to check the type of an entity. Luckily, this is easy to do.

This article shows how to check the type of:

typescript check type

How to check the type of a variable?

To check the type of a variable in TypeScript, you can use the typeof operator.

This operator returns the data type of a variable.

Here are a few examples of the typeof operator in action:

typescript// Outputs: 'string' console.log(typeof 'dog'); // Outputs: 'boolean' console.log(typeof false); // Outputs: 'number' console.log(typeof 123); // Outputs: 'object' console.log(typeof 'asd'>); // Outputs: 'function' console.log(typeof function ( ) <>); // Outputs: 'function' console.log(typeof class A <>); // Outputs: 'object' console.log(typeof null); // Outputs: 'undefined' console.log(typeof undefined);

This method is reliable for checking primitive types, but you need to use other methods to check the type of a class or an object.

Note: Here, we are using the JavaScript typeof operator, which is different from the TypeScript typeof operator.

How to check the type of an object?

To check the type of an object, you can use the in keyword to verify if a specific property or method exists inside the object.

typescriptconst cow = < giveMilk: () => < console.log('give milk.') > >; const dog = < bark: () => < console.log('bark.') > >; // Outputs: true console.log('giveMilk' in cow); // Outputs: false console.log('bark' in cow);

In this example, we verify that the object is a cow by checking for the existence of the giveMilk function.

You can also use a tagged or discriminated union to check an object’s type.

The best Web Development course in 2023! 👉 Learn Web Development

How to check the type of an interface?

To check the type of a TypeScript interface, you can:

You can read more about checking the type of an interface in this article.

How to check a class type?

To check the type of a class in TypeScript, you can use the instanceof operator.

This operator returns a boolean (true or false) and tests if an object is of the specified object type.

typescriptclass Dog < public constructor( private name: string ) < >> const dog = new Dog('doggy'); // Outputs: true console.log(dog instanceof Dog);

Unfortunately, this method isn’t bulletproof and can return false positives.

A safer option to check the class type is to create a class constant with the class name inside the class.

typescriptclass Dog < public readonly NAME = 'dog'; public constructor( private name: string ) < >> const dog = new Dog('doggy'); // Outputs: true console.log(dog.NAME === 'dog');

You can also create a type guard to check for specific methods to test the class type.

How to check the type of an array?

To check the type of an array, you need to verify each array’s item type individually and look for inconsistent types.

typescriptconst isArrayOfStrings = (value: unknown): value is string[] => < return Array.isArray(value) && value.every(item => typeof item === "string"); > // Outputs: true console.log(isArrayOfStrings(['a','b'])); // Outputs: false console.log(isArrayOfStrings(['a',2]));

In this example, we verify that each array item is of type string.

Final thoughts

As you can see, checking the type of an entity is easy in TypeScript.

You can choose from multiple options, depending on your situation.

typescript check type

Here are some other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Читайте также:  Php true type font
Оцените статью