【发布时间】:2021-06-30 12:48:21
【问题描述】:
我有一个 API 路由(使用 Next.js API routes),成功时具有特定响应形状,发生错误时具有特定响应形状。
export type ApiErrorResponse = { message: string };
export type SuccessResponse = {
user: UserSession | null;
};
export type GetCurrentUserHandlerResponse = ApiErrorResponse | SuccessResponse;
const getCurrentUserHandler: NextApiHandler<GetCurrentUserHandlerResponse> = () => { /* ... */ };
如何根据错误告诉 Axios 响应的形状?
当我像这样抽象出请求时:
const getCurrentUserRoute = '/api/user';
const getCurrentUserRequest = () =>
axios.get<GetCurrentUserHandlerResponse>(getCurrentUserRoute);
并使用getCurrentUserRequest 我总是必须区分.then 和.catch 的响应是成功形式还是错误形式。
理想情况下,我正在寻找这样的东西:
const getCurrentUserRequest = () =>
axios.get<SuccessResponse, ApiErrorResponse>(getCurrentUserRoute);
最终我希望 TypeScript 能够做到这一点:
getCurrentUserRequest()
.then((response) => {
// now TS knows response.data is of the shape { user: UserSession | null; }
})
.catch((error) => {
// now TS knows error.response.data is { message: string; }
});
有没有办法用 TypeScript 做到这一点?
【问题讨论】:
标签: typescript axios