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'
添加回答
舉報