我正在构建用于将我的react应用程序与后端服务连接的API,并且我想使用Typescript来指定data
Axios请求内部的类型。如何在不修改其他字段的情况下更新Axios响应内的数据类型(请参见下面的代码中的getAllProjects)?
const generateApiInterface = ()=>{
let headers: any= {
'Content-Type': 'application/json',
};
if(token){
headers={
'Authorization': 'Token '+ token,
...headers //append other basic proprieties
}
}
return axios.create({
baseURL: baseURL,
headers: headers
});
}
const backend = generateApiInterface();
//DATA
export const getAllProjects = async () : Promise<AxiosResponse<?????>> => backend.get('/projects/');
简单地分配所需的类型(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'.
尝试
export const getAllProjects = async () => backend.get<string[]>('/projects/')
对于其他上下文,Axios请求公开以下接口:
request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>
的形状AxiosResponse
是
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
这样,他们就可以采用通用类型参数,该通用类型参数可用于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
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句