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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With