不知request中动态添加属性的方法,如何用typescript重写?
来源:2-10 axios二次封装(下)

aleke
2021-06-14
这个方法:
['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
request[item] = (url, data, options) => {
return request({
url,
data,
method: item,
...options
})
}
})
不知如何使用typescript重写?
自己试了后,
function request(options: AxiosRequestConfig) {
options.method = options.method || 'get'
if (options.method.toLowerCase() === 'get') {
options.params = options.data
}
if (config.env === 'prod') {
service.defaults.baseURL = config.baseApi
} else {
service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
}
return service(options)
}
const actions = ['get', 'post', 'put', 'delete', 'patch']
actions.forEach((item) => {
request[item] = (url, data, options) => {
return request({
url,
data,
method: item,
...options
})
}
})
会显示以下这个错误提示:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '(options: AxiosRequestConfig) => AxiosPromise<any>'.
No index signature with a parameter of type 'string' was found on type '(options: AxiosRequestConfig) => AxiosPromise<any>'.ts(7053)
(parameter) item: string
谢谢!
写回答
1回答
-
河畔一角
2021-06-15
初步判断是因为request返回的类型是 AxiosPromise<any> ,它不能挂载string类型,比如get/post
我目前没有配置过ts环境,所以我咱不能提供解决方案。
00
相似问题