首页 > 解决方案 > 是否可以在 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 和逻辑的方法,我也很乐意听到。

标签: javascripttypescriptreduxtyping

解决方案


推荐阅读