Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should i use a predicate as a return type instead of a boolean?

I just found out about user defined typeguards while reading this article: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

In one of the examples in this article they use pet is Fish as a method return type which is a predicate.

I found out that instead of this return type one can just as well use boolean. So is the parameter is Type returntype just syntactic sugar or does it have a specific use?

like image 387
Maurice Avatar asked Oct 20 '25 01:10

Maurice


1 Answers

If you return a boolean the function will be a simple function that is not a typeguard. The pet is Fish syntax is what signals to the compiler that this function will impact the type of the argument.

For example :

class Fish { f: boolean }
class Dog { d: boolean; }

declare let x: Fish | Dog;
declare function isFish(p: Fish | Dog): boolean
declare function isFishGuard(p: Fish | Dog): p is Fish;

if (isFishGuard(x)) {
    x.f // x is Fish
}

if (isFish(x)) {
    x.f // error x is still Fish|Dog
}

Playground link

like image 78
Titian Cernicova-Dragomir Avatar answered Oct 22 '25 04:10

Titian Cernicova-Dragomir