Reputation: 11508
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. 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
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[]>
:
What am I missing?
Upvotes: 4
Views: 13247
Reputation: 10892
I think the problem is caused by duck typing, TypeScript is not able to guess the return type correctly from the expressions.
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]);
}
Upvotes: 4