[英]Typescript - “… is not a function or its return value is not iterable”
I have this helper function: 我有这个辅助功能:
export function to(promise: Promise<any>) {
return promise
.then((data: any) => [null, data])
.catch((err: Error) => [err, null]);
}
This function (in theory) should help me catch errors while using await
in functions. 这个函数(理论上)应该可以帮助我在函数中使用await
时发现错误。 for example: 例如:
const [err, data] = await to(validate(card));
The problem is that on runtime, I get the following error: 问题是在运行时,出现以下错误:
to is not a function or its return value is not iterable to不是函数或其返回值不可迭代
While the expected return signature should be Promise<[Error, null]> Promise<[null, Error]>
, it looks like returns (again, in theory, because it actually fails): Promise<any[] | Error[]>
尽管预期的返回签名应为Promise<[Error, null]> Promise<[null, Error]>
,但它看起来像返回(理论上,因为它实际上失败了): Promise<any[] | Error[]>
Promise<any[] | Error[]>
: Promise<any[] | Error[]>
:
What am I missing? 我想念什么?
I think the problem is caused by duck typing, TypeScript is not able to guess the return type correctly from the expressions. 我认为问题是由鸭子输入引起的,TypeScript无法从表达式中正确猜测返回类型。
You can type it explicit: 您可以明确输入:
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.