Using a user-defined type guard

In situations where we can't use the other type guards, we can create our own. We can do this by creating a function with the return type as type predicate. We actually used a user-defined type guard earlier in the book when we went through the unknown type.

Let's implement the example from the last two sections using our own type guard function:

  1. We have the same interfaces and union type:
interface IPerson {
id: number;
firstName: string;
surname: string;
}

interface ICompany {
id: number;
name: string;
}

type PersonOrCompany = IPerson | ICompany;
  1. So, let's implement the type guard function that returns whether the object is of type IPerson:
function isPerson(personOrCompany: PersonOrCompany): personOrCompany is IPerson {
return "firstName" in personOrCompany;
}

The type predicate personOrCompany is IPerson helps the TypeScript compiler narrow down the type. To confirm this, hovering over personOrCompany in the first branch should give the IPerson type.  If we then hover over personOrCompany in the second branch, we should get the ICompany type. 

Creating a user-defined type guard is a little more work than the other methods, but it gives us lots of flexibility to deal with cases if the other methods don't work.

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

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