Yok*_*jay 8 javascript frontend typescript reactjs axios
const fetcher = Axios.create()
fetcher.interceptors.response.use(config=>{
return config.data
})
Run Code Online (Sandbox Code Playgroud)
类型fetcher.get('...')是AxiosInstance,但实际上是AxiosInstance.data类型
那么我怎样才能正确地改变类型呢?
Lah*_*hah 10
import axios from 'axios'
declare module 'axios' {
export interface AxiosInstance {
request<T = any> (config: AxiosRequestConfig): Promise<T>;
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
head<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
}
}
Run Code Online (Sandbox Code Playgroud)
{
"compilerOptions": {
"typeRoots": [
"./node_modules/@types",
"./src/types/",
]
}
}
Run Code Online (Sandbox Code Playgroud)
fetcher.get<DataType>('...')并且您应该得到提到的类型的响应。这个解决方案可能有效!另请查看此线程以了解更多信息! 解决方案参考
无需重新定义模块。
假设您的拦截器执行了response => response.data并且服务器响应如下:
{
book: { id: 42 }
}
Run Code Online (Sandbox Code Playgroud)
这应该足够了:
type Book = {
id: number
}
type ResponseContainer = {
book: Book
}
request.post<unknown, ResponseContainer>('/api')
.then(({ book }) => console.log(book.id))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9127 次 |
| 最近记录: |