FOR DEVELOPERS

Typescript: How to Check Type of Objects & Variables

Typescript How to Check Type of Objects & Variables

Many developers are embracing TypeScript to build scalable applications because it enforces static typing. However, when working with variables or objects of the union type, you may want to narrow these types down to do something more specific, and knowing how to check these types is the first step.

In this article, we’ll explore techniques for checking the type of objects and variables in TypeScript. From using the ‘in operator’ to the typeof operator, you will have everything you need to get your object and variable types.

Interested in Typescript content? How about exploring Typescript+Python opportunities too?

Importance of type-checking your objects and variables

Here are some of the reasons why you should type-check your objects and variables:

  • To avoid type-related errors: TypeScript is a strongly typed language, which means that type safety is enforced at compile time. By checking the types of objects and variables, you can catch type-related errors early on and prevent your application from bugs at runtime.
  • To ensure type compatibility: By checking the types of objects and variables, you can improve the logic function and stability of your code ensuring that your code works as you expect it to.
  • Improved readability: Type annotations in TypeScript make your code more self-explanatory and explicit. Using operators such as the in operator, instanceof operator, or typeof operator can make it even easier for other developers to understand and modify your code

Ways to check the type of objects and variables

In TypeScript, you can use several operators to check the type of objects and variables. These operators include:

The in operator

The in operator provides a way to determine if an object has a specific property with a given name. This can be useful for dynamically accessing the properties of an object, or for checking the existence of a property before using it.

For example, if you run a small e-commerce store that sells jeans, you can use the in operator to check if your stock object contains three properties: products, price, and availability. If all three properties exist, you can log a message to your customers indicating that the product is in stock along with its price. If any of the properties are missing, you can also log a message indicating that the product is out of stock.

interface Stock {
  product: string;
  price: number;
  availability?: boolean;
}

function Purchase(Stock: Stock) { if ("product" in Stock && "price" in Stock && "availability" in Stock) { console.log( This ${Stock.product} is in stock and the price is $${Stock.price} ); } else { console.log(This product is out of stock); } }

Purchase({ product: "Jean", price: 50, available: true }); //output - This Jean is in stock and the price is $50

Purchase({ product: "Jean", price: 80}); //output - This product is out of stock

With the in operator, you can easily check whether an object contains specific properties before accessing them, which can help prevent runtime errors and ensure the stability of your code.

The instanceof operator

The instanceof operator in TypeScript can be used to determine whether or not a value is an instance of another value or class. It's particularly useful while dealing with complex data structures where you have to compare a value to a constructor function or class.

For example, let's say you're developing a music application that allows users to create any of these types of accounts: free and premium. However, each account provides the user with a unique set of features, and you'd want to determine which type of account the user has, in order to show them their appropriate music content. You can start by defining two classes, FreeAccount and PremiumAccount. And each of these accounts will have its own set of properties and methods:

class FreeAccount {
  username: string;
  email: string;
  constructor(username: string, email: string) {
    this.username = username;
    this.email = email;
  }
}

class PremiumAccount { username: string; email: string; subscriptionStartDate: Date; constructor(username: string, email: string, subscriptionStartDate: Date) { this.username = username; this.email = email; this.subscriptionStartDate = subscriptionStartDate; } }

When the user logs in, you would want to check which type of account they have and show them the contents they subscribed to, and you can do that with the instanceof operator.

const userAccount = login();
if (userAccount instanceof FreeAccount) {
console.log('Welcome to the free account!');
// show free account features
} else if (userAccount instanceof PremiumAccount) {
console.log('Welcome to the premium account!');
// show premium account features
} else {
console.log('Invalid account type!');
// handle error
}

Overall, using the instanceof operator can help you to handle different types more effectively, especially when working with complex data structures, where you have to check if an object contains certain properties before using it in your code.

The typeof operator

The typeof operator is a standard JavaScript operator recognized by TypeScript for checking the type of variables and objects. It returns a string indicating the type of the operand's value, which can be useful for narrowing down variable types and performing more specific operations based on the type information.

You may have complex cases where a variable can take on multiple types and you need to handle each type case differently. With the typeof operator, you can check each type and execute different logic accordingly. For instance:

function displayValue(value: string | number | boolean | object){
  if (typeof value === "string") {
console.log(`The value is a string: "${value}"`);

} else if (typeof value === "number") {

console.log(`The value is a number: ${value}`);

} else if (typeof value === "boolean") {

console.log(`The value is a boolean: ${value}`);

} else if (typeof value === "object") {

console.log(`The value is a object: ${value}`);

} else {

console.log(`The value is of unsupported type: ${typeof value}`);

}

}

console.log(displayValue("Hello")) //output - The value is a string: "Hello"

console.log(displayValue(5)) //output - The value is a number: 5

console.log(displayValue(true)) //output - The value is a boolean: true

console.log(displayValue({name:"test"}) // output - The value is an object: object

In this case, we defined a function with an if-else block that checks the type of the value parameter using the typeof operator. If the value parameter is of a specific type, the function will display both the type and the actual value to the console.

However, only use the typeof operator to check the type of primitive values or variables in TypeScript because it cannot distinguish between an array, or an object, and when you have to get the type of objects, stick to using other type-checking techniques such as the instanceof operator or the in operator.

Conclusion

Knowing how to check the type of variables and objects is important when working with TypeScript, and with this simple how-to guide, you will be able to use the typeof operator, instanceof operator, and the in operator to get the types of your objects and variables in TypeScript.

Author

  • Typescript: How to Check Type of Objects & Variables

    Jessica Joseph

    Written by Jessica Joseph, a skilled front-end developer, and technical writer, with a unique blend of a year of experience in both technical writing and web development.

Frequently Asked Questions

The process of ensuring that the types of objects or variables used in a program are correct and conform to the expected types is known as type-checking.

In TypeScript, you can use the in operator, instanceof operator, and typeof operator to check the type of objects and variables.

Yes! The typeof operator can be useful for checking the type of primitive values such as strings, numbers, and booleans. However, when working with objects, classes, and arrays, it may not work as expected. In these cases, you may want to consider using other type-checking techniques such as the instanceof operator or the in operator.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.