angular - 为什么我应该使用谓词作为返回类型而不是布尔值?
问题描述
我刚刚在阅读这篇文章时发现了用户定义的类型保护:https ://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
在本文的一个示例中,它们pet is Fish
用作方法返回类型,即谓词。
我发现代替这种返回类型,也可以使用boolean
. 那么parameter is Type
返回类型只是语法糖还是有特定用途?
解决方案
如果您返回 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
}
推荐阅读
- email - 如何通过 Digital Ocean 上的外部 SMTP 服务发送电子邮件?
- javascript - 无法保存,因为列中有值(不允许使用“WR#”(它不在合法值列表中)
- java - Struts2 和 PI4J
- java - 我如何实现从 API 下载文件
- c# - 一旦页面加载,asp.net页面上的加载图标就会消失
- python - boolean.conjugate() 有什么用?
- vba - MSXML2.ServerXMLHTTP.6.0 PATCH 请求的 Open 方法存在问题
- linux - /proc/ 中的 VmLck(锁定内存)与 VmPin(固定内存)
/地位 - sqf - 使用 SQF 在 Arma 3 中编辑虚拟军械库
- python - 从字符串中获取时间