Dynamic redux middleware typescript error : The expected type comes from property 'type' which is declared here on type 'AppActions'

Dynamic redux middleware typescript error : The expected type comes from property 'type' which is declared here on type 'AppActions'

我正在使用 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}`));
};

我在 type dispatch({ 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

我该如何解决这个错误?

经过一些搜索,我找到了一个 用于在 Typescript 4.1+ 中使用如下函数制作动态字符串:

function makeType<NS extends string, N extends string>(namespace: NS, name: N) {
  return namespace + name as `${NS}${N}`
}
// should be used like this
const sampleType = makeType('REQUEST_', 'POSTS');
// return "REQUEST_POSTS"

然后为了获取字符串作为类型,并从对象生成动态字符串应该使用 as const 像这样:

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" },
} as const;

有了这个技巧,当你输入 BankPages.post.name 时,你会看到 "POSTS" 而不是 string

动态调度应该是这样的:

dispatch({ type: makeType("REQUEST_", BankPages[page].name) });