Home > database >  Is it possible to set return type of a function to be the return type of it's callback function
Is it possible to set return type of a function to be the return type of it's callback function

Time:11-23

I have the following function

export const tryAsyncAwait = async (fn: () => any) => {
  try {
    const data = await fn();
    return [data, null];
  } catch (error) {
    return [null, error];
  }
};

If I pass in this function...

const getNum = (x: number) => x * 2

I would like typescript to infer the return type of tryAsyncAwait to be return: [number, null]

CodePudding user response:

For the desired behavior the function should have the following type signature:

export const tryAsyncAwait = async <F extends () => any>(
    fn: F
): Promise<[ReturnType<F>, null]> => {
    try {
        const data = await fn();
        return [data, null];
    } catch (error) {
        return [null, error];
    }
};

But since there is an alternate return in the catch block, the type must be a union of the resolved and rejected value in order to be correct.

export const tryAsyncAwait = async <F extends () => any>(
    fn: F
): Promise<[ReturnType<F>, null] | [null, unknown]> => {
    try {
        const data = await fn();
        return [data, null];
    } catch (error) {
        return [null, error];
    }
};

Also, keep in mind the return type must be wrapped in a Promise as async is used in the function definition. As the call to fn is awaited, this assumes other async functions can be passed as a callback. The type signature () => any is wide enough to cover these cases.

  • Related