是否可以遍历Typescript中的类型值并基于它们生成新的类型?

时间:2019-04-16 11:04:30

标签: javascript typescript redux typing

我正在尝试为我的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和逻辑的方法,我也希望听到。

0 个答案:

没有答案