javascript - 是否可以在 Typescript 中迭代类型值并基于它们生成新类型?
问题描述
我正在尝试为我的 redux 创建类型定义,ACTION_HANDLERS
我需要获取所有操作的类型。我有一个动作联合类型,它包含动作类型和有效负载类型,但我找不到任何关于如何迭代和提取它们的示例。
我不确定是否可以这样做,但也许有人可以帮助找到解决方案。
import generateReducer from '@/utils/generateReducer';
import action, { ActionsUnion } from '@/utils/action';
const initialState = {};
const ADD = '[elements] ADD';
const REFRESH = '[elements] REFRESH';
export const ActionCreators = {
add: action<typeof ADD, { elementIds: string[] }>(ADD),
refresh: action(REFRESH)
};
// This is what I'm trying to create types for
const ACTION_HANDLERS = {
[ADD]: (state, { payload }) => ({ ...state, ...payload }),
};
export default generateReducer(ACTION_HANDLERS, initialState);
// Here are some useful types to explain everything better
const ActionCreators: {
add: ActionWithPayloadFn<"[elements] ADD", { elementIds: string[]; }>;
refresh: ActionFn<"[elements] REFRESH">;
}
// ActionCreators with no keys
type ActionsUnion = ActionWithPayload<"[elements] ADD", { elementIds: string[]; }> | Action<"[elements] REFRESH">
// How can I use the 'ActionsUnion' type above to generate something like:
type ActionHandlers = {
"[elements] ADD": (state: any, ActionWithPayload<"[elements] ADD", { elementIds: string[] }>) => any,
"[elements] refresh": (state: any, Action<"[elements] refresh">) => any
}
// Here is some pseudo-code:
type ActionHandlers<StateType, ActionsUnion> = {
const resultType = {};
for (let i = 0; i < ActionsUnion.length; i++) {
resultType[ActionsUnion[i].type] = (state: StateType, action: ActionsUnion[i]) => StateType
}
return resultType;
}
// So I would be able to use it like so:
const ACTION_HANDLERS: ActionHandlers<MyStateType, ActionsUnion> = {...}
如果有更好的输入 redux store 和逻辑的方法,我也很乐意听到。
解决方案
推荐阅读
- laravel - 从 Vue 组件取回数据
- gitlab - 完成后gitlab中的作业状态
- java - Spring JPA 规范-arg-resolver
- scala - IntelliJ 工作表期间的循环定义错误
- arrays - 合并 2 个具有相似键的 JSON 对象:ReactJS
- java - 如何使用 Java 转储 MySQL 数据库?
- javascript - 如何让我的表单在用户键入时指示模式不匹配错误(自定义验证错误)?
- javascript - AsyncFunction.apply 不是函数
- c - 用 union 的大小定义指向内存的指针
- .net - 将找到平均值的 Sql Query 迁移到 .Net Entity Framework Query