0

我正在寻找一种方法来推断作为参数传递的回调函数的返回类型。目的是实现一个异步操作处理程序钩子,它可以调用 rtk-query 突变函数并以结构化方式返回响应,其中我们有一个errororsuccess响应。

沙箱:https ://codesandbox.io/s/rtk-hook-ts-0bue6

钩子代码看起来像(必须增强它以T从传递的 rtk 钩子推断):

type UseAsync<T, A extends unknown[]> = [
  (...args: A) => Promise<{ success?: T; error?: iApiErrorHandlerReturnType }>,
  {
    data: T | null;
    isLoading: boolean;
    error?: iApiErrorHandlerReturnType;
  }
];

const useAsyncAction = <T, A extends unknown[] = any>(
  callback: (...args: A) => MutationActionCreatorResult<any> // Update it to infer resposne from generic type T
): UseAsync<T, A> => {
  const [isLoading, setLoading] = React.useState<boolean>(false);
  const [data, setData] = React.useState<T | null>(null);
  const [error, setError] = React.useState<iApiErrorHandlerReturnType>();
  const [handleError] = useApiErrorHandler();

  const asyncCallback = React.useCallback(
    async (...args: A) => {
      try {
        setLoading(true);
        const response = await callback(...args).unwrap();
        console.log(response);
        setData(response as T);
        setError(undefined);
        setLoading(false);
        return { success: response as T };
      } catch (e) {
        const errors = handleError(e as iBaseQueryErrorResponse);
        setError(errors);
        setLoading(false);
        return { error: errors };
      }
    },
    [handleError, callback]
  );

  return [asyncCallback, { data, isLoading, error }];
};
4

0 回答 0