Axios + Typescript:如何传递“ResponseType”类型的参数?

rea*_*ebo 3 typescript axios

axios 定义ResponseType

export type ResponseType = 
  | 'arraybuffer' 
  | 'blob' 
  | 'document' 
  | 'json' 
  | 'text' 
  | 'stream'
Run Code Online (Sandbox Code Playgroud)

我正在尝试将配置传递给 axios.post

const config = {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Host': HOST_HEADER,
        },
        responseType: 'json'
 }

 const data_to_post = { .... omitted ... }

 return axios.post(HOST, data_to_post, config)
Run Code Online (Sandbox Code Playgroud)

问题:打字稿 linter 警告我说类型字符串不能分配给类型 ResponseType。

还尝试过:当然我不能使用语法

 responseType: ResponseType.json
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Phi*_*lip 6

问题是 Typescript 会推断config出类型

{
    headers: {
        'X-Requested-With': string;
        'Content-Type': string;
        'Host-Header': string;
    };
    responseType: string;
}
Run Code Online (Sandbox Code Playgroud)

Typescript 不知道您正在尝试为 Axios 创建配置对象。您可以将整个对象显式键入为AxiosRequestConfig,也可以显式键入responseType: 'json'为 be 类型ResponseType

const config: AxiosRequestConfig = {
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host-Header': 'dsa',
  },
  responseType: 'json'
};
Run Code Online (Sandbox Code Playgroud)