I have an API route (using Next.js API routes) that has a certain response shape when successful and another when an error occurs.
export type ApiErrorResponse = { message: string };
export type SuccessResponse = {
user: UserSession | null;
};
export type GetCurrentUserHandlerResponse = ApiErrorResponse | SuccessResponse;
const getCurrentUserHandler: NextApiHandler<GetCurrentUserHandlerResponse> = () => { /* ... */ };
How can I tell Axios what the shape of the response is depending on the error?
When I abstract away the request like this:
const getCurrentUserRoute = '/api/user';
const getCurrentUserRequest = () =>
axios.get<GetCurrentUserHandlerResponse>(getCurrentUserRoute);
and use getCurrentUserRequest I always have to distinguish in both .then and in .catch whether the response is of the success shape, or of the error shape.
Ideally I'm looking for something like this:
const getCurrentUserRequest = () =>
axios.get<SuccessResponse, ApiErrorResponse>(getCurrentUserRoute);
Ultimately I want TypeScript to be able to do this:
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; }
});
Is there a way to do that with TypeScript?