[英]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.