gpt4 book ai didi

reactjs - 如何创建动态 typescript 类型 : The expected type comes from property 'type' which is declared here on type 'AppActions'

转载 作者:行者123 更新时间:2023-12-04 03:44:58 25 4
gpt4 key购买 nike

我正在使用 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: ... }) 上收到错误:预期的类型来自此处声明的属性“type”在类型“AppActions”上

这是我的类型:

export const REQUEST_POSTS = "REQUEST_POSTS";

export interface RequestPosts {
type: typeof REQUEST_POSTS;
}

一切都很完美,我知道这是因为我声明了 typeof REQUEST_POSTS

我该如何修复这个错误?

最佳答案

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

关于reactjs - 如何创建动态 typescript 类型 : The expected type comes from property 'type' which is declared here on type 'AppActions' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65324786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com