【问题标题】:Having issue with typing a return type of fetching function键入获取函数的返回类型时出现问题
【发布时间】:2023-01-12 06:24:40
【问题描述】:

我制作了一个异步自定义函数包装器,负责处理返回401 unauthorized 的响应。 我如何正确输入我的获取函数的 return type 以使我的 data 从 useQuery 推断出该类型?

// ASYNC WRAPPER

type HandlerType = (args?: any) => Promise<any>;

export const asyncWrapper =
  (handler: HandlerType) =>
  async (args?: any): Promise<any> => {
    try {
      const result = await handler(args);
      return result;
    } catch (err: any) {
      if (err.response.status === 401) {
        // refresh token then again call handler
        await sessionService.refreshToken();
        const result = await handler(args);
        return result;
      }
    }
  };



//FETCHING REQUEST

export type QuestionsType = {
  answerOptions: {
    _id: string;
    answerText: string;
    isCorrect: boolean;
  };
  questionText: string;
};

const getQuestions = asyncWrapper(
    async (difficulty: string): Promise<QuestionsType[]> //type not working => {
      const token = localStorage.getItem("accessToken");

      try {
        const response = await axios.get("/questions", {
          headers: {
            Authorization: token,
          },
        });

        return response.data;
      } catch (e) {
        throw new Error("Custom");
      }
    }
  );
const { data } = useQuery(["quiz"], quizService.getQuestions); // data type is "any"

【问题讨论】:

  • 不要使用any。使用泛型。

标签: javascript reactjs typescript types async-await


【解决方案1】:

使用泛型来打字,here is a playground

export const asyncWrapper =
  <A, R>(handler: (args: A) => Promise<R>) =>
  async (args: A): Promise<R> => {
    try {
      return handler(args);
    } catch (err: any) {
      if (err.response.status === 401) {
        // refresh token then again call handler
        return handler(args);
      }
    }
    throw new Error("Handle this")
  };



//FETCHING REQUEST

export type QuestionsType = {
  answerOptions: {
    _id: string;
    answerText: string;
    isCorrect: boolean;
  };
  questionText: string;
};

const getQuestions = asyncWrapper(
    async (difficulty: string): Promise<QuestionsType[]> => {
      const token = localStorage.getItem("accessToken");

      try {
        return [];
      } catch (e) {
        throw new Error("Custom");
      }
    }
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-20
    • 2020-08-06
    • 2016-07-01
    • 2018-11-06
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多