为了账号安全,请及时绑定邮箱和手机立即绑定

Typescript 返回类型(布尔值、'is' 与 <nothing>)差异?

Typescript 返回类型(布尔值、'is' 与 <nothing>)差异?

喵喔喔 2023-10-14 10:06:25
需要一些帮助来理解它。功能有什么区别foo(type: any): type is number和:foo(type: any): boolean和:foo(type: any)?谢谢
查看完整描述

2 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

当你这样做时


foo(type: any)

这只是一个简单的函数定义。如果可以的话,TS 将推断返回值的类型。


foo(type: any): boolean

是一个函数定义,添加了返回值foo应该是布尔值的断言。(如果 TS 推断返回值不是布尔值,则会抛出错误。通常,这是没有必要的。)


foo(type: any): type is number 

和上面两个完全不同。它允许调用者缩小传递foo表达式的类型。这称为类型保护。例如,对于最后一个实现,您可以执行以下操作:


const something = await apiCall();

// something is unknown

if (foo(something)) {

  // TS can now infer that `something` is a number

  // so you can call number methods on it

  console.log(something.toFixed(2));

} else {

  // TS has inferred that `something` is not a number

}

您只能使用某种: type is number语法来执行上述操作 - 其他两个定义foo不允许调用者缩小范围。


查看完整回答
反对 回复 2023-10-14
?
临摹微笑

TA贡献1982条经验 获得超2个赞

这意味着您的函数需要布尔值作为参数:


function foo(arg: boolean){

  if(typeof arg != 'boolean'){

    Throw 'type error'

  } else {

    return arg

  }

}

这意味着您的函数将返回一个布尔值:


function foo(): boolean {

  return true;

}


let value: string;


value = foo();


//Type Error, variable value (type 'string') not assignable to type 'boolean'


查看完整回答
反对 回复 2023-10-14
  • 2 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信