actionCreatorFactory.ts 1009 B

12345678910111213141516171819202122232425262728293031323334
  1. import { Action } from 'redux';
  2. const allActionCreators: string[] = [];
  3. export interface ActionOf<Payload> extends Action {
  4. readonly type: string;
  5. readonly payload: Payload;
  6. }
  7. export interface ActionCreator<Payload> {
  8. readonly type: string;
  9. (payload: Payload): ActionOf<Payload>;
  10. }
  11. export interface ActionCreatorFactory<Payload> {
  12. create: () => ActionCreator<Payload>;
  13. }
  14. export const actionCreatorFactory = <Payload>(type: string): ActionCreatorFactory<Payload> => {
  15. const create = (): ActionCreator<Payload> => {
  16. return Object.assign((payload: Payload): ActionOf<Payload> => ({ type, payload }), { type });
  17. };
  18. if (allActionCreators.some(t => (t && type ? t.toLocaleUpperCase() === type.toLocaleUpperCase() : false))) {
  19. throw new Error(`There is already an actionCreator defined with the type ${type}`);
  20. }
  21. allActionCreators.push(type);
  22. return { create };
  23. };
  24. // Should only be used by tests
  25. export const resetAllActionCreatorTypes = () => (allActionCreators.length = 0);