And*_*zo1 4 typescript reactjs axios
data我正在构建 API 以将我的 React 应用程序与后端服务连接起来,并且我想使用 TypeScript 来指定Axios 请求内部的类型。如何在不修改其他字段的情况下更新 Axios 响应中的数据类型(请参阅下面代码中的 getAllProjects)?
class MyApi {
constructor(token: string | null) {
let headers: any = {
'Content-Type': 'application/json',
};
if (token) {
headers = {
...headers, //append other basic proprieties
'Authorization': 'Token ' + token
}
}
this.baseEndpoint = axios.create({
baseURL: `${baseURL}`,
headers: headers
});
}
//DATA
const getAllProjects = async () : Promise<AxiosResponse<?????>> => this.baseEndpoint.get('/projects/');
}
Run Code Online (Sandbox Code Playgroud)
简单地分配所需的类型(假设data: string[]本例)会引发以下错误:
Argument of type 'string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type 'string[]' is not assignable to type 'never[]'.
Type 'string' is not assignable to type 'never'.
Run Code Online (Sandbox Code Playgroud)
Arm*_*ran 13
尝试
export const getAllProjects = async () => backend.get<string[]>('/projects/')
Run Code Online (Sandbox Code Playgroud)
对于其他上下文,Axios 请求的类型如下:
request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>
Run Code Online (Sandbox Code Playgroud)
其中 anAxiosResponse被定义为
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
Run Code Online (Sandbox Code Playgroud)
这允许它们采用通用类型参数,该参数可用于指定data给定响应的属性类型,如下所示:
type Data = {
A: string
B: number
C: boolean
// Etc.
}
Axios.get<Data>(endpoint).then(response => {
const { data } = response // Data
data.a // string
data.b // number
data.c // boolean
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19885 次 |
| 最近记录: |