[英]TypeScript with redux-thunk and axios
我正在尝试将我的应用程序转换为 TypeScript,我已经到了最后一部分,我需要重构仅处理 API 请求的ApiClient
文件。
这是一个简化版本:
import axios from "axios";
import * as types from "../types/types"
import * as routes from "../constants/ApiRoutes"
// axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
// axios.defaults.headers.common["Accept"] = "application/json";
const apiClient = {
getComments: function (callback: Function) {
return axios
.get(routes.GET_COMMENTS_URL)
.then((response) => response.data)
.then(callback) // this throws an error
.catch((err) => console.log(err));
},
};
export default apiClient;
// this is the code in action creators
export function fetchCommentsAction(callback: Function) {
return function (dispatch: Function) {
apiClient.getComments((comments: types.Comment[]) => {
dispatch(commentsReceivedSuccess(comments));
});
if (callback) {
callback();
}
};
}
当从服务器收到响应时,回调 function 运行,但问题是如果我将回调类型Function
,我会收到一条错误消息,提示Argument of type 'Function' is not assignable to parameter of type '(value: never) => PromiseLike<never>'.
什么是快速解决这个问题的方法?
谢谢!
我认为您不应该使用“函数”,它太抽象了。 您可以键入带有“() => void”的 function,其中 void 是返回类型。
所以在你的情况下我会尝试类似的东西:
getComments: function (callback: (value: any) => Promise<any>) {
编译器还告诉您尝试(value: never) => PromiseLike<never>
,我会先尝试。
这是有关键入回调的文档的链接: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#return-types-of-callbacks
理想情况下,您应该键入您的请求返回的响应 object,并且您应该避免使用never
或any
..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.