【发布时间】:2021-05-06 11:59:17
【问题描述】:
我正在构建 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'.
【问题讨论】:
标签: reactjs typescript axios