Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
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?
Here are some of the reasons why you should type-check your objects and variables:
In TypeScript, you can use several operators to check the type of objects and variables. These operators include:
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 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 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.
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.
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.