指定axios响应数据类型



我正在构建API来连接我的react应用程序和我的后端服务,我想使用typescript来指定我的Axios请求中data的类型。如何在不修改其他字段的情况下更新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/');
}

简单地赋值所需的类型(本例中假设为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'.

Try

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
})

最新更新