Using the instanceof keyword 

The instanceof keyword is another JavaScript keyword. It checks whether an object has a particular constructor function. It is typically used to determine whether an object is an instance of a class.

Let's go through an example:

  1. We have two classes representing Person and Company:
class Person {
id: number;
firstName: string;
surname: string;
}

class Company {
id: number;
name: string;
}
  1. We also have a union type combining both of these classes:
type PersonOrCompany = Person | Company;
  1. We now need to write a function that takes in a Person or Company and outputs their name to the console:
function logName(personOrCompany: PersonOrCompany) {
if (personOrCompany instanceof Person) {
console.log(`${personOrCompany.firstName} ${personOrCompany.surname}`);
} else {
console.log(personOrCompany.name);
}
}

When using instanceof, we have the variable we are checking before it and the constructor name (the class name) after it.

If we hover over personOrCompany in the first branch, we get the Person type: 

If we hover over personOrCompany in the second branch, we get the Company type:

So, instanceof is great for narrowing down the type if we are dealing with classes. However, there are lots of TypeScript types we use that aren't JavaScript types or based on classes. So, what do we do in these situations? Let's find out in the following sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.139.169