[英]Why is the ReturnType of 'value is Type' function boolean?
我想讓 function 接收值並運行類型保護 function。
const checkType = (string: string) : string is 'a' => string === 'a'
/// const checkType: (string: string) => string is "a"
const getType = (value: 'a' | 'b') => checkType(value);
/// const getType: (value: 'a' | 'b') => boolean
我預計getType
的返回類型為string is 'a'
但它被斷言為boolean
。
{value} is {Type}
可以在一個 function 中工作嗎?
不能傳送到另一個function嗎?
返回類型string is 'a'
只是傳達 typescript 它是一個類型保護。 無論如何,它都會返回boolean
,因為類型保護用於在運行時確認類型。
不能傳送到另一個function嗎?
是的,您可以在if
語句中添加保護 function,如下所示。 這將確保如果防護檢查在運行時通過,它實際上確認它是給定的類型。
const isLiteralA = (string: string) : string is 'a' => string === 'a'
function myFunction(stringValue: string) {
if (isLiteralA(stringValue)) {
// Any operation on `stringValue` inside this if statement will assume it to be
// the string literal "a" since stringValue passed the guard check for the same
}
else {
// If `stringValue` does not pass the guard check, do something else (if required)
}
}
您可以參考: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.