You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Angular NgRx的ActionGroup中提取所有动作类型

如何为NgRx createActionGroup生成统一的动作类型

当你用createActionGroup定义动作组后,不用逐个手动声明每个动作的类型,借助TypeScript泛型和ReturnType就能一次性生成所有动作的联合类型,具体实现如下:

1. 你的动作组定义(参考)

import { createActionGroup, emptyProps, props } from '@ngrx/store';

// 假设已定义SomeType类型
type SomeType = { /* 你的类型定义 */ };

export const myCustomActions = createActionGroup({
  source: 'Source name',
  events: {
    'My action': emptyProps(),
    'My action Succeed': props<{ parameter: SomeType }>(),
    'My action Failed': props<{ error: Error }>()
    // 更多动作可继续添加
  }
});

2. 生成统一的动作联合类型

定义一个泛型类型工具,自动遍历动作组的所有动作并提取类型:

// 类型工具:提取动作组中所有动作的ReturnType并合并为联合类型
type ActionGroupActions<T> = {
  [K in keyof T]: ReturnType<T[K]>;
}[keyof T];

// 为你的动作组生成统一类型
export type MyCustomActionsType = ActionGroupActions<typeof myCustomActions>;

3. 使用这个统一类型

你可以在reducer或其他需要动作类型的地方直接使用MyCustomActionsType,TypeScript会自动识别每个动作的参数类型:

type MyState = {
  data?: SomeType;
  error?: Error;
};

function myReducer(state: MyState = {}, action: MyCustomActionsType): MyState {
  switch (action.type) {
    case myCustomActions.myAction.type:
      return { ...state, error: undefined };
    case myCustomActions.myActionSucceed.type:
      // action.parameter会自动推导为SomeType类型
      return { ...state, data: action.parameter, error: undefined };
    case myCustomActions.myActionFailed.type:
      // action.error会自动推导为Error类型
      return { ...state, error: action.error };
    default:
      return state;
  }
}

内容的提问来源于stack exchange,提问作者pitruskjw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 13:52:12