首页 > 解决方案 > 为什么我应该使用谓词作为返回类型而不是布尔值?

问题描述

我刚刚在阅读这篇文章时发现了用户定义的类型保护:https ://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

在本文的一个示例中,它们pet is Fish用作方法返回类型,即谓词。

我发现代替这种返回类型,也可以使用boolean. 那么parameter is Type返回类型只是语法糖还是有特定用途?

标签: angulartypescript

解决方案


如果您返回 aboolean该函数将是一个不是类型保护的简单函数。pet is Fish语法是向编译器发出此函数将影响参数类型的信号。

例如 :

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
}

游乐场链接


推荐阅读