Wrapper Funcion that Receives and Executes Generic Funcion Returns Error When Executing

  Kiến thức lập trình

I have a wrapper function that recieves an async generic function and runs it, but it doesn’t honor the return type. In this case, the generic function returns a type of response and the wrapper function has a return type annotation that indicates the return of te result of the generic inner function. The code runs and works well but typescript yells that it cannot be assigned.

interface Response {
  status: "error" | "success";
  message?: string;
  data?: any;
}


export const actionWrapper = async <
  T extends (...args: any[]) => Promise<Response>,
>(
  action: T,
): Promise<Awaited<ReturnType<T>>> => {
    const res = await action();
    return res;
};

Playground Code: https://www.typescriptlang.org/play?ssl=16&ssc=1&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgEoQM4AcD2IMoDeAUMshmHGAK4YBcyARNFDlI8gD5MbUJIYMjANylkAW0wY4AcwgB+BhSigZosgBMqcRcjggAnqIC+xMxAAeuKGGQI8FPQjDA8AdShwsWaMgC8ehgGIAjIADxiACrIlpAgGhjIABQAdGlwUDL0eoYA2gC6AJT+AHzIAAqs4sAEYejYDhAlADTEJUliiC54DJGthQyVONW1AIIA7nDAkBp1EDRQIJEGPmGRJRulyCRkZPb4tlCY-nqT007dIEmF6rtHCyDIRxgmokA

LEAVE A COMMENT