Skip to content
This repository has been archived by the owner on Jan 10, 2018. It is now read-only.

feat(switchReduce): Added type safety way to reduce state #416

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

gionkunz
Copy link

@gionkunz gionkunz commented May 14, 2017

I've been trying to work out a preferred solution for me when dealing with reducers. I wanted to have type safety so that I don't need to guess what the payload of an action is. This is the result which I currently use in my project and I think it would be valuable for many other developers. Also I think switch is the worst language construct that ever existed (right after goto) and I believe we should try to reduce the amount of developers who need to use it. It's error prone, unsafe and a complete syntax mess. This is an example of how to use switchReduce in conjunction with TypedAction<T> which I've also added to the README.md. What do you think?

import { ActionReducer, TypedAction, switchReduce } from '@ngrx/store';

export class AddAction implements TypedAction<number> {
  readonly type = 'ADD';
  constructor(public readonly payload: number) {}
}
export class SubtractAction implements TypedAction<number> {
  readonly type = 'SUBTRACT';
  constructor(public readonly payload: number) {}
}
export class ResetAction implements TypedAction<any> {
  readonly type = 'RESET';
  readonly payload: any;
  constructor() {}
}

export const counterReducer: ActionReducer<number> =
  (state: number = 0, action: TypedAction<any>) =>
    switchReduce(state, action)
      .byClass(AddAction, (num: number) => {
        return state + num;
      })
      .byClass(SubtractAction, (num: number) => {
        return state - num;
      })
      .byClass(ResetAction, () => {
        return 0;
      })
      .reduce();

@gionkunz
Copy link
Author

I just saw this is somewhat an extension to #382

@gionkunz gionkunz changed the title feat(switchReduce): Added type safty way to reduce state feat(switchReduce): Added type safety way to reduce state May 14, 2017
@jotatoledo
Copy link

jotatoledo commented May 15, 2017

Currently on my reducer functions I can always see the type of the payload. The only thing that isnt type safe on my current project is the return of the toPayload function when I call map with it as argument on any observable.

Does this solves the describe problem with toPayload by any luck? That would be awesome

@gionkunz
Copy link
Author

I guess the operator could be extended in such a way, ill take a look

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants