Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. interface Action<T> {
  2. type: T;
  3. }
  4.  
  5. interface PayloadAction<T, R> {
  6. readonly type: T;
  7. payload: R;
  8. }
  9.  
  10. interface ActionFactory<T> {
  11. (): Action<T>;
  12. type: T;
  13. }
  14.  
  15. interface PayloadActionFactory<T, R> {
  16. (payload: R): PayloadAction<T, R>;
  17. type: T;
  18. }
  19.  
  20. function newActionFactory<T extends string>(type: T|''): ActionFactory<T>;
  21. function newActionFactory<T extends string, R>(type: T|'', payloadFunc: (payload: R) => R): PayloadActionFactory<T, R>;
  22. function newActionFactory<T extends string, R>(type: T|'', payloadFunc?: (payload: R) => R): ActionFactory<T> | PayloadActionFactory<T, R> {
  23. const actionBuilder = payloadFunc ?
  24. <PayloadActionFactory<T, R>> function(payload: R): PayloadAction<T, R> {
  25. return {
  26. payload: payloadFunc(payload),
  27. type: <T>type
  28. };
  29. } :
  30. <ActionFactory<T>> function(): Action<T> {
  31. return { type: <T>type };
  32. }
  33. ;
  34.  
  35. actionBuilder.type = <T>type;
  36.  
  37. return actionBuilder;
  38. }
  39.  
  40. //usage
  41.  
  42. const Action1 = newActionFactory('ACTION1');
  43. /* Here we have to use a function mostly for typings but also allow user to define some logic to build the payload */
  44. const Action2 = newActionFactory('ACTION2', (p: number) => p);
  45.  
  46. /* Here we need to do some boilerplate by repeting the structure or our actions
  47. * This should be replaced with ts 2.3 with something like :
  48. * `type Actions = returnType Action1 | returnType Action2`
  49. */
  50. type Actions = Action<'ACTION1'> | PayloadAction<'ACTION2', number>;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement