首页 > 解决方案 > 使用正文在 post 请求上指定 Axios 响应类型

问题描述

我正在尝试同时指定 JSON 正文和响应类型(它们是不同的,那里的一些样本不知何故两者都相同)。

错误信息:

'{ grant_type: string; 类型的参数 refresh_token:字符串;}' 不可分配给“AuthResponse”类型的参数。
对象字面量只能指定已知属性,并且“AuthResponse”类型中不存在“grant_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;
}

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是 type{grant_type: ..., refresh_token: ...}而不是AuthResponse.

从普通的 JS 示例中,数据是请求的主体,但不知道为什么它会被强制与响应相同,所以我一定做错了什么。

编辑/回答: 正如@jrsharpe 的评论所指出的,这是一个错误,他们几个小时前也刚刚发布了v0.23.0 。它修复了错误 #4116。所以只需升级到 0.23.0+。

标签: typescriptpostaxiosrequest

解决方案


你可以像这样输入

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

}

推荐阅读