简体   繁体   中英

Having issue with typing a return type of fetching function

I made an async custom function wrapper that takes care of response returning 401 unauthorized . How do i properly type return type of my fetching function to make my data from useQuery infer that type?

// 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"

Use generics to type it, 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");
      }
    }
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM