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不允许调用者缩小范围。
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'
添加回答
举报