Mike K
Mike K

Reputation: 6511

How to properly setup axios client with Typescript?

This is what I have so far:

type TRequest = {
    url: string;
    method?: EMethodTypes;
    params?: TParams;
    body?: TBody;
};

export const httpClient = async <Result>(
    { url, method = EMethodTypes.GET, params = {}, body = {} }: TRequest
): Promise<AxiosResponse<Result>> =>
    await axios({
        url,
        method,
        params,
        data: JSON.stringify(body),
        headers: {
            'Content-Type': 'application/json',
        }
      });

But when I attempt to make a request as,

const { user, token } = await httpClient<{user: TUser; token: string}>({
  url: apiRoutes.POST.AUTH.LOGIN,
  method: EMethodTypes.POST,
  body: formData,
});

I get an error,

const { user, token } = await httpClient<{user: TUser; token: string}>({
        ^^^^
Property 'user' does not exist on type 'AxiosResponse<{ user: any; token: string; }>'.

Not sure what I'm doing wrong here, considering that I do have both of those properties indicated.

Upvotes: 2

Views: 985

Answers (2)

Buczkowski
Buczkowski

Reputation: 2416

I'm not familiar with axios but from types: https://github.com/axios/axios/blob/master/index.d.ts#L76

it means that if you want to get user you need to take it from AxiosResponse.data.

Upvotes: 0

Rafi Henig
Rafi Henig

Reputation: 6422

Like all http-clients, the response body is a nested property inside the response (in this case data), modify your code as demonstrated below:

const { data: { user, token } } = await httpClient<{ user: TUser; token: string }>({
  url: apiRoutes.POST.AUTH.LOGIN,
  method: EMethodTypes.POST,
  body: formData,
})

Or optionally:

const { user, token } = (await httpClient<{ user: TUser; token: string }>({
  url: apiRoutes.POST.AUTH.LOGIN,
  method: EMethodTypes.POST,
  body: formData,
})).data

Upvotes: 1

Related Questions