![](/img/trans.png)
[英]Why does Angular 2's CanActivate return an Observable<boolean> instead of a Promise?
[英]Why should i use a predicate as a return type instead of a boolean?
我在閱讀本文時發現了用戶定義的類型保護: https ://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
在本文的一個示例中,他們使用pet is Fish
作為方法返回類型,這是一個謂詞。
我發現不是這個返回類型,我也可以使用boolean
。 那么parameter is Type
返回類型只是語法糖還是具有特定用途?
如果返回一個boolean
該函數將是一個不是打字機的簡單函數。 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.