[英]Multiple / compound return types
做這個
function foo(): () => void | string
意思是,那個
a) 函數foo
可能返回一個字符串,或另一個不返回任何內容的函數; 或者
b) 函數foo
返回另一個函數,該函數又可能返回也可能不返回字符串?
另外,您如何正確並清楚地表示另一個選項(無論哪個選項不正確)?
function foo(): () => void | string
function foo(): () => void | string
: foo 是一個沒有輸入參數的函數,它將返回另一個結果為 void 或 string 的函數
function foo(): void | string
function foo(): void | string
: foo 是一個沒有輸入參數的函數,它將返回 void 或 string
function foo(): (() => void) | string
function foo(): (() => void) | string
: foo 是一個沒有輸入參數的函數,它將返回字符串或另一個返回 void 的函數
() => void | string
() => void | string
是可能返回也可能不返回字符串的函數類型,這似乎不是很有用,因為返回字符串的函數已經可以分配給() => void
。
如果你想要“函數或字符串”,你應該使用方括號: (() => void) | string
(() => void) | string
,就像在任何其他情況下要使用不按優先級順序使用運算符的情況下使用括號的方式相同。
這意味着 (b)
/**
* The function foo returns another function,
* which in turn may or may not return a string.
*/
function foo(): () => void | string;
// example implementation
function foo(): () => void | string {
return () => {
if (Math.random() % 2 === 0) {
return "bar";
}
};
}
以下是您如何定義 (a)
/**
* The function foo may return a string,
* or another function which doesn't return anything.
*/
function foo2(): (() => void) | string;
// example implementation
function foo2(): (() => void) | string {
if (Math.random() % 2 === 0) {
return "bar";
}
return () => {};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.