DEV Community

Cover image for Typescript Type Predicate
thomas for This is Angular

Posted on • Updated on • Originally published at Medium

Typescript Type Predicate

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 Animal which can either be a Cat or a Dog:

interface Cat {
  name: string;
}
interface Dog {
  name: string;
  breed: string;
}
type Animal = Dog | Cat;
Enter fullscreen mode Exit fullscreen mode

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

As shown below, Typescript can narrow our input Animal to Dog and 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 Dog or undefined values. 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>.

filter without type predicate

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[].

filter with type predicate


I hope you learned new Angular concept. If you liked it, you can find me on Medium, Twitter or Github.

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

Happy coding !!!

Top comments (0)