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

How to use with tagged union types? #38

Open
mattdistefano opened this issue Jan 25, 2017 · 3 comments
Open

How to use with tagged union types? #38

mattdistefano opened this issue Jan 25, 2017 · 3 comments

Comments

@mattdistefano
Copy link

Assume we have a reducer using tagged union types - i.e. function reducer(state: AppState, action: ActionTypeA | ActionTypeB | ActionTypeC): AppState { return state; } - and wanted to handle a router action. This doesn't seem to work out of the box since the actions are untyped.

@brandonroberts
Copy link
Member

This should still work in your reducer. The type is still a string.

  switch (action.type) {
    case foo.ActionTypes.BAR:
      return Object.assign({}, state, { foo: bar });

    case routerActions.UPDATE_LOCATION:
      return state;

    default:
      return state;
  }

@mattdistefano
Copy link
Author

The problem with that usage is that it seems to break the type inference magic typescript does w/ the union types and consequently I lose type checking on the action payload.

@brandonroberts
Copy link
Member

brandonroberts commented Feb 2, 2017

I see. I'll looking to adding typed actions soon. You can also create your own typed action and use it in the reducer.

import { Action } from '@ngrx/store';
import { type } from '../utils/type';
import { routerActions, RouterMethodCall } from '@ngrx/router-store';

export const ActionTypes = {
  FOO: type('[Category] Foo'),
  UPDATE_LOCATION: type(routerActions.UPDATE_LOCATION)
};

export class ActionTypeA implements Action {
  type = ActionTypes.FOO;

  constructor(public payload?: boolean) {}
}

export class UpdateLocationAction implements Action {
  type = ActionTypes.UPDATE_LOCATION;

  constructor(public payload: { path: string }) {}
}

export type Actions = ActionTypeA | UpdateLocationAction;

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

No branches or pull requests

2 participants