Issue
I want to get return type of fn
which is generic for my errorbound
function.
I tried
type ErrorBound = <Fn extends Function>(Fn) => Promise<ReturnType<typeof Fn> | Error>;
export const errorBound: ErrorBound = async (fn) => {
try {
return await fn();
} catch (e) {
console.error("errorBound!!");
console.error({ e });
return e
}
};
I want it be like
const foo = errorBound(() => 1) // foo is now Promise<number | Error>
But currently foo
is Promise<any>
Solution
Try this:
const errorBound = <T>(fn: (...args: any[]) => T): T | Error => {
try {
return fn();
} catch(e) {
console.log({e})
if (!(e instanceof Error)) return new Error(`Not an Error: ${e}`);
return e;
}
}
- It looks easier to generize the return type rather than the function itself
- You don't need to
return await somePromise
it's equivalent toreturn somePromise
e
is not always an error, it's valid JS tothrow 10
orthrow 'not an Error object'
, so I added a check
Answered By - Nino Filiu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.