@ngrx/store (an observable redux implementation for angular (2) ) utilizes a specific pattern to assign the correct type to a reducer.
Check out the actual code here.
export const ActionTypes = {
FOO: type('foo'),
BAR: type('bar')
};
export class FooAction implements Action {
type = ActionTypes.FOO;
constructor(public payload: string) { }
}
export class BarAction implements Action {
type = ActionTypes.BAR;
constructor(public payload: number) { }
}
export type Actions
= Foo
| Bar;
This also includes a sample reducer:
export class SomeReducerState {
foo: string;
bar: number;
}
const initialState = {
foo: undefined,
bar: 0
};
export function someReducer(
state: SomeReducerState = initialState,
action: some.Actions
): SomeReducerState {
switch (action.type) {
case some.ActionTypes.FOO:
return Object.assign({}, state, { foo: action.payload });
case some.ActionTypes.BAR:
return Object.assign({}, state, { bar: action.payload });
default:
return state;
}
}
In TypeScript 2.0.x, the switch/case structure was used to determine the proper type for action.payload
. For example, inside case some.ActionTypes.FOO
, action.payload
was assigned as string
, while in BAR
it was number
. However, with TypeScript 2.1.x, it appears to default to any
. Is there a workaround to achieve the same outcomes in 2.1.x? Or is it potentially a bug?