【发布时间】:2021-09-30 15:23:31
【问题描述】:
我如何在 Flow 中精确键入以下函数,该函数要么接受回调并稍后使用某个值调用它,要么不接受任何参数并返回该值的 Promise?
const foo = callback => {
const p = Promise.resolve(1.0);
if (callback === undefined) {
return p;
}
p.then(callback);
}
};
我尝试使用类似 in 的交集类型:
type CallbackCase = ((number) => void) => void;
type PromiseCase = () => Promise<number>;
const foo: CallbackCase & PromiseCase =
callback => {
const p = Promise.resolve(1.0);
if (callback === undefined) {
return p;
}
p.then(callback);
};
但随后 Flow 抱怨(https://flow.org/try 的最新版本也是如此):
Cannot assign function to `foo` because undefined [1] is incompatible with `Promise` [2] in the return value. [incompatible-type]
那么我该如何解决这个问题?
更新:此签名的原因是我们有较旧的代码,其中函数正在接受回调。我们希望将其转换为 Promise 形式,同时仍支持年长的调用者。在转换过程中,我们希望保持类型精确。特别是在呼叫站点,应仅允许以下两种形式:
let a: Promise<number> = foo();
foo(callback);
任何其他形式都应该被拒绝。
【问题讨论】:
-
链接到流尝试报告没有错误,一切都好吗? )
标签: flowtype intersection