Home > database >  Typescript get generic function's return type
Typescript get generic function's return type

Time:09-01

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>

CodePudding user response:

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;
    }
}

Playground

  • It looks easier to generize the return type rather than the function itself
  • You don't need to return await somePromise it's equivalent to return somePromise
  • e is not always an error, it's valid JS to throw 10 or throw 'not an Error object', so I added a check

CodePudding user response:

type F = <T>(fn: (...args: any[]) => T) => Promise<T | Error>
const f: F = async (fn) => {
    return fn()
}
const ff = () => Math.random()
const n = f(ff) // Promise<number | Error>
  • Related