我正在使用Typescript和react-redux,并尝试为我的API请求定制动态中间件。
下面是我的代码:
import { Dispatch } from "react";
import { errorHandler } from "../components/Layout/SnackBar/alert";
import { API } from "../_helpers/api";
import { getTheTime } from "../_helpers/constants";
import { AppActions, AppState } from "../_types";
export const BankPages = {
posts: { name: "POSTS", api: "/post/v2" },
lessons: { name: "LESSONS", api: "/lesson/v2" },
guides: { name: "GUIDES", api: "/lesson/v2/guide" },
courses: { name: "COURSES", api: "/lesson/v2/course" },
exercises: { name: "EXERCISES", api: "/lesson/v2?course=125" },
};
export const requestBank = (page: keyof typeof BankPages) => (
dispatch: Dispatch<AppActions>,
getState: () => AppState
) => {
const bankState = getState().bank[page];
const currentTime = getTheTime();
const resetTime = currentTime - bankState.nextLoad;
if (bankState.data && resetTime <= 0) {
return;
}
dispatch({ type: `REQUEST_${BankPages[page].name}` });
API.get(BankPages[page].api)
.then((res) =>
dispatch({
type: `SUCCESS_${BankPages[page].name}`,
payload: {
data: res.data,
nextLoad: getTheTime(10),
},
})
)
.catch((err) => errorHandler(err, `FAILURE_${BankPages[page].name}`));
};
typedispatch({ type: ... })
出现错误:The expected type comes from property 'type' which is declared here on type 'AppActions'
个
这是我喜欢的类型:
export const REQUEST_POSTS = "REQUEST_POSTS";
export interface RequestPosts {
type: typeof REQUEST_POSTS;
}
一切都很完美,我知道这是因为我声明了typeof REQUEST_POSTS
。
如何修复此错误?
1条答案
按热度按时间pxy2qtax1#
经过一番搜索,我找到了一个way,用于在Typescript 4.1+中使用如下函数生成动态字符串:
然后,为了获取字符串作为类型,并从对象中生成动态字符串,应该像这样使用
as const
:使用此技巧,当您键入
BankPages.post.name
时,将显示"POSTS"
而不是string
而动态调度应该是这样的: