繁体   English   中英

为什么'value is Type'的ReturnType是function boolean?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM