Typescript Type Predicate

Thomas Laforge
3 min readDec 4, 2022

--

Sometimes in our code, we want to have more control over the type we are manipulating and we want to tell Typescript that choice.

Let’s create a union Type Animalwhich can either be a Cator a Dog:

interface Cat {
name: string;
}
interface Dog {
name: string;
breed: string;
}
type Animal = Dog | Cat;

Let’s say, we want to write a function to concatenate all available information inside each interface to a string. To archive this, we need to narrow our variable to the correct type.

To define this narrowing, we need to write a function where the return type is a type predicate defined with the “is” keyword.

// We can search for a property only available in one of our interfaces, 
// and if this property exists (breed in this case)
// we can categorically say that our return type is of type Dog
isDog(animal: Animal): animal is Dog {
return (animal as Dog).breed !== undefined;
}

As shown below, Typescript can narrow our input Animalto Dogand give us a nice autocomplete.

autocomplete because input is of dog Type

But what makes Typescript really strong is that it now knows that the else statement cannot be of type Dog. So the type is narrowed to Cat.

autocomplete for cat Type

Bonus Tip: Type predicate can become very useful for filter operations. (array.filter or rxjs.filter). Typescript doesn’t narrow your type correctly after a filter operation because it doesn’t really know if the type was narrowed with that operation. But as a developer, you know what type of output is expected. Then you can just use a type predicate to control your type system.

In the following snippet, we have an array of Dogor undefinedvalues. We want to filter out all undefined values to get an array of dogs. Without a type predicate, the output is still of type Array<Dog|undefined>.

But by telling Typescript that we are sure the output IS of type Dog[], we can write a type predicate as the return type, and Typescript will infer the output to Dog[].

If you found this article useful, please consider supporting my work by giving it some claps👏👏 to help it reach a wider audience. Don’t forget to share it with your teammates who might also find it useful. Your support would be greatly appreciated.

I hope you learned new Typescript concept. You can find me on Medium, Twitter or Github. Don’t hesitate to ping me if you have more questions

👉 If you want to accelerate your Angular and Typescript learning journey, come and check out Angular challenges.

Happy coding !!!

--

--

Thomas Laforge

Software Engineer | GoogleDevExpert in Angular 🅰️ | #AngularChallenges creator