How To Check Types In Typescript
Tags: typescript, javascript, webdev
Published: 2022-08-10 07:56:00

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.

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


```typescript
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](https://www.typescriptlang.org/docs/handbook/2/typeof-types.html) 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.

```typescript

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.

```typescript
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);
```

Works perfect, move to the final task.

> Learn more about [instanceof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/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.


```typescript
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 [Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html)

## 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 ](https://gist.github.com/danywalls/19aba5c23ee5ee5158b98d63a770d2d4)