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

需要一些帮助来理解它。

功能有什么区别

foo(type: any): type is number

和:

foo(type: any): boolean

和:

foo(type: any)

?

谢谢


喵喔喔
浏览 153回答 2
2回答

繁星点点滴滴

当你这样做时foo(type: any)这只是一个简单的函数定义。如果可以的话,TS 将推断返回值的类型。foo(type: any): boolean是一个函数定义,添加了返回值foo应该是布尔值的断言。(如果 TS 推断返回值不是布尔值,则会抛出错误。通常,这是没有必要的。)foo(type: any): type is number&nbsp;和上面两个完全不同。它允许调用者缩小传递foo表达式的类型。这称为类型保护。例如,对于最后一个实现,您可以执行以下操作:const something = await apiCall();// something is unknownif (foo(something)) {&nbsp; // TS can now infer that `something` is a number&nbsp; // so you can call number methods on it&nbsp; console.log(something.toFixed(2));} else {&nbsp; // TS has inferred that `something` is not a number}您只能使用某种: type is number语法来执行上述操作 - 其他两个定义foo不允许调用者缩小范围。

临摹微笑

这意味着您的函数需要布尔值作为参数:function foo(arg: boolean){&nbsp; if(typeof arg != 'boolean'){&nbsp; &nbsp; Throw 'type error'&nbsp; } else {&nbsp; &nbsp; return arg&nbsp; }}这意味着您的函数将返回一个布尔值:function foo(): boolean {&nbsp; return true;}let value: string;value = foo();//Type Error, variable value (type 'string') not assignable to type 'boolean'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript