Toguard
Toguard

Reputation: 447

Specify Axios response type on post request with body

I'm trying to specify both the JSON body and the response type (which are different, some samples out there somehow have the same for both).

Error message:

Argument of type '{ grant_type: string; refresh_token: string; }' is not assignable to parameter of type 'AuthResponse'.
Object literal may only specify known properties, and 'grant_type' does not exist in type 'AuthResponse'.

Here's the response I defined as my type:

export interface AuthResponse {
  token: string;
  token_type: string;

  access_token: string;
  access_token_expires_at: string;

  refresh_token: string;
  refresh_token_expires_at: string;
}

Use of axios:

axios
      .post<AuthResponse>(
        secrets.authURL,//Defined in enclosing class
        {
          grant_type: this.grantType,//Defined in enclosing class
          refresh_token: this.authPayload,//Defined in enclosing class
        },//<-- Defined as data and conflicts with AuthResponse
        {
          headers: {
            Authorization: this.getAuthHeader(),//Defined in enclosing class
            "Content-Type": this.contentType,///Defined in enclosing class
          },
        }
      )
      .then((axiosResp) => {
        const response = axiosResp.data;//<-- Not the type I'd expect
      });

axiosResp.data is of type {grant_type: ..., refresh_token: ...} instead of AuthResponse.

From the plain JS samples, data is the body for the request, but not sure why it would be forced as being the same for the response, so I must be doing something very wrong.

Edit/Answer: As pointed by @jrsharpe's comment, this IS a bug, they also just released v0.23.0 a few hours ago. It fixes the bug #4116. So just upgrade to 0.23.0+.

Upvotes: 3

Views: 7205

Answers (1)

Jerome
Jerome

Reputation: 2761

you can type both like this

interface AuthResponse {
    token: string;
    token_type: string;

    access_token: string;
    access_token_expires_at: string;

    refresh_token: string;
    refresh_token_expires_at: string;
}

interface TBody {
    grant_type: string
    refresh_token: string
}

const t = async (): Promise<void> => {

    const data = await axios.post<AuthResponse, AxiosResponse<AuthResponse, TBody>, TBody>("theurl", {
        grant_type: 'kjkjk',
        refresh_token: "dddf",
    }, {
        headers: {
            Authorization: "dfdfds",
            "Content-Type": "application/json",
        },
    })

    const resu: AuthResponse = data.data

}

Upvotes: 4

Related Questions