redux 如何创建动态打字脚本类型:所需的类型来自此处对类型“AppActions”声明的属性“type”

idfiyjo8  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(149)

我正在使用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
如何修复此错误?

pxy2qtax

pxy2qtax1#

经过一番搜索,我找到了一个way,用于在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) });

相关问题