DEV Community 👩‍💻👨‍💻

Cover image for How To Check Types In Typescript
Dany Paredes
Dany Paredes

Posted on • Updated on • Originally published at danywalls.com

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.

In Typescript, we have three ways to work with it using:

  • typeof: the keyword helps to check values 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 an 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> = [];

Enter fullscreen mode Exit fullscreen mode

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 with a ternary into the createInvoice function.

function createInvoice(
  description: string | number,
  amount: number,
  country
): Invoice {
  const descriptionValue =
    typeof description === "number" ? `${description}` : description;
  return {
    description: descriptionValue,
    amount,
    country,
  };
}

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
  }
}

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Works perfect, move to the final task.

Learn more about instanceof

Using Type Guards

For the last two approaches, we use typeof and instanceof, which help us with values 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 to tell 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);
  }
});

Enter fullscreen mode Exit fullscreen mode

Learn more about Type Guards

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 you in future type checking.

Full source code

Oldest comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!