我正在构建 API 以将我的 React 应用程序与我的后端服务连接起来,我想使用 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
})
关于reactjs - 指定 axios 响应数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66007441/