例如,我正在研究更好的型別謂詞以及它們如何通過 實際縮小型別pet is Fish。
我試圖創建一個簡單的打字稿游樂場
在doSomething我使用isFish功能。
isFish表示為具有回傳型別pet is Fish,但如果我使用它并將結果分配給變數,則結果有點“強制轉換”為 a boolean。所以我猜pet is Fish可以看作是一個型別本身。
所以我的問題是:(或任何類似的運算式)可以被視為布林值的子pet is Fish型別,就像?"Hello world"string
type X = "hello world" | string;
// ^? type X = string
type Y = "hello world" & string;
// ^? type Y = "hello world"
謝謝!
uj5u.com熱心網友回復:
不,這并不等同于 const 字串。布林值只有兩個可能的值,即boolean與 相同,除了只有ortrue | false之外,您不能縮小該型別。truefalse
我認為型別保護是一種特殊的語法,一個類似isFish(pet: Cat | Dog | Fish): pet is Fish回傳布林值的函式,編譯器知道該布林值是否true是pet變數實際上是 a Fish,或者如果false它不是 a Fish,并縮小pet變數的型別例如:
const pet: Cat | Dog | Fish = getPet();
if (isFish(pet) {
// pet now has type Fish
} else {
// pet now has type Cat | Dog
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481027.html
標籤:打字稿
上一篇:使用打字稿不顯示預覽影像
