【问题标题】:Typescript extend HTTP Response interfaceTypescript 扩展 HTTP 响应接口
【发布时间】:2021-05-05 15:14:17
【问题描述】:

所以我使用axios 库有以下代码:

const BTrustURLResponse: Response = await axios.get(`${process.env.BTRUST_URL}/flow/${process.env.BTRUST_FLOWID}/link?callback_url=${callback_url}`, {
    headers: {
        'Authorization': `Bearer ${process.env.BTRUST_API_KEY}`,
    },
});

我确定 (console.log(Object.keys(BTrustURLResponse))) 返回的对象具有属性 data。但默认Response 接口不包含data 属性。

我该如何解决?

我尝试了以下方法:

  1. 创建@types 目录,使用response 目录,然后:

这是文件本身:

 declare global {
    export interface Response {
        data?: string,
    }
}
  1. 然后我在tsconfig.json 做了以下:"typeRoots": ["@types", "./node_modules/@types"]

但我仍然无法将.dataResponse 一起使用。

【问题讨论】:

标签: node.js typescript


【解决方案1】:

您不必创建单独的@types 文件来创建Response 接口。 Axios 有一个名为AxiosResponse<T> 的泛型接口,它从get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>; 中获取T 泛型变量。然后T 泛型变量用于datadata 属性AxiosResponse

看到这个:

interface ResponseData{
  _id?: string
  //... or any "property" you wanna add
}

const BTrustURLResponse = await axios.get<RespnseData>(`${process.env.BTRUST_URL}/flow/${process.env.BTRUST_FLOWID}/link?callback_url=${callback_url}`, {
    headers: {
        'Authorization': `Bearer ${process.env.BTRUST_API_KEY}`,
    },
});

希望它有效...

【讨论】:

    【解决方案2】:

    https://github.com/axios/axios 文档看起来data: {} 是一个对象,但您使用字符串作为数据对象的类型。 data?: string,这可能是个问题。 如果您不知道响应的结构,那么作为开始可以使用 data?: any ,如果可行,那么您可以提供正确类型的 data 对象。

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 2020-06-09
      • 2016-07-06
      • 2017-10-21
      • 2020-04-09
      • 2018-06-20
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多