【发布时间】: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