Home > Software engineering >  Having issue with typing a return type of fetching function
Having issue with typing a return type of fetching function

Time:01-13

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"

CodePudding user response:

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");
      }
    }
  );
  • Related