我有这个辅助功能:
export function to(promise: Promise<any>) {
return promise
.then((data: any) => [null, data])
.catch((err: Error) => [err, null]);
}
这个函数(理论上)应该可以帮助我await
在函数中使用时发现错误。例如:
const [err, data] = await to(validate(card));
问题是在运行时,出现以下错误:
to不是函数或其返回值不可迭代
尽管预期的返回签名应该是Promise<[Error, null]> Promise<[null, Error]>
,但它看起来像是返回(理论上再次,因为它实际上失败了)Promise<any[] | Error[]>
::
我想念什么?
我认为问题是由鸭子输入引起的,TypeScript无法从表达式中正确猜测返回类型。
您可以明确输入:
function to(promise: Promise<any>): Promise<[Error, any]> {
return promise
.then((data: any) => [null, data] as [Error, any])
.catch((err: Error) => [err, null] as [Error, any]);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句