How To Check Types In Typescript

In Typescript, we have to check for values types like boolean, string, object instance from class, and the values in objects.
šš½ Why pay for hosting? Click here to deploy your Angular apps for free on a reliable VPS
In Typescript, we have three ways to work with it using:
-
typeof: the keyword helps to check value types, like boolean, string, number, etc.
-
instanceof: the keyword to compare the object instance with a class constructor.
-
type guards: The powerful way to check types using typescript feature language.
Scenario
We are building accounting software with the entity class Invoice in the application code.
class Invoice {
public amount: number;
public description: string;
country: string;
}
class SalesInvoices extends Invoice {
products: Array<string> = [];
}
class PurchaseInvoice extends Invoice {
tax: number;
}
const invoicesToProcess: Array<Invoice> = [];One team wants us to work on some tasks.
-
Create a function support number or string for the description field.
-
Create a function to add only SalesInvoice into the invoiceToProcess array.
-
Iterate the invoiceToProcess and print all invoices if the country is "ES" and the amount is more than 100.
The idea is to use typeof, instanceof, and type guards for each task. Let's do it:
Using TypeOf
The operator typeof helps us to compare JavaScript value types; because the amount parameter is a string or number, we use typeof a ternary in the createInvoice function.
function createInvoice(
description: string | number,
amount: number,
country
): Invoice {
const descriptionValue =
typeof description === "number" ? `${description}` : description;
return {
description: descriptionValue,
amount,
country,
};
}We now have a function, support string, and number in the description.
const invoiceWithNumber = createInvoice(1231321, 120, "ES");
const invoIceWithString = createInvoice("Banana", 90, "USA");
console.log(invoIceWithString, invoiceWithNumber);Perfect, let's move to step two.
Learn more about typeof and values types.
Using InstanceOf
Our challenge is only to add SalesInvoice into the invoicesToProcess, because salesInvoice extends from Invoice. The invoiceToProcess understands any invoice parameter and extends form Invoice from the invoice is valid.
The instanceof operator comes to help us because it compares class instances.
function addInvoiceToProcess(invoice: Invoice) {
if (invoice instanceof SalesInvoices) {
invoicesToProcess.push(invoice);
}
}The operator instanceof compares the constructor with the SalesInvoice if it matches, we push the invoice to the array. Let's test our code.
const salesInvoice = new SalesInvoices();
salesInvoice.amount = 100;
salesInvoice.country = "ES";
const basicInvoice = new Invoice();
basicInvoice.amount = 90;
basicInvoice.country = "USA";
addInvoiceToProcess(basicInvoice);
addInvoiceToProcess(salesInvoice);
console.log(invoicesToProcess);It works; move to the final task.
Learn more about instanceof
Using Types Predicates
For the last two approaches, we use typeof and instanceof, which helps us with value types or instances, but what about the values?
The final challenge is to print if the country is "ES" and the amount is more than "100," and we use the type guards for it.
The type guards is a function with the is operator, using an assertion, tells the compiler it fits with some type.
function isValidInvoice(invoice: Invoice): invoice is SalesInvoices {
return invoice.amount > 100 && invoice.country === "ES";
}
// the code looks clean.
invoicesToProcess.forEach((invoice) => {
if (isValidInvoice(invoice)) {
console.log(invoice);
}
});Learn more about Types Predicates
Recap
We learned how to deal with type checking in Typescript and used the type guards to write assertion functions to make the code clean and easy to follow.
I hope it helps in future type-checking.
Related Articles
3 Ways of Type Transformation in Typescript
When we use types or interfaces, the typescript compiler enforces the object fit with them to avoid runtime errors for missing fields. Sometimes we want the flexibility to create an object without breaking the contract with the interface type. For ex...
Abstract Classes in Typescript
In Typescript, the classes can inherit from another class to share methods and properties between classes. Also, Typescript support abstract class. Let me show you why and when to use it. For example, we have a base class Subscription and create the ...
Avoid Check Null or Undefined In Typescript using Optional Chaining and Nullish Coalescing
TypeScript offers powerful features that make code more concise and efficient. Two such features, optional chaining and nullish coalescing, play a vital role in handling data effectively. In this article, we'll explore these features within the conte...
Real Software. Real Lessons.
I share the lessons I learned the hard way, so you can either avoid them or be ready when they happen.
Join 13,800+ developers and readers.
No spam ever. Unsubscribe at any time.