@ ngrx / store(angular(2)的可观察到的redux实现)使用此模式将适当的类型传递给reducer
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;
以及减速器:
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;
}
}
它在typescript 2.0.x中的工作方式是(我认为)它将使用switch / case来决定/过滤出什么是正确的类型action.payload
,所以insidecase some.ActionTypes.FOO
action.payload
是string
,insideBAR
是number
。现在使用打字稿2.1.x似乎是any
。有什么方法可以用2.1.x达到相同的结果?那是个错误吗?
方法是使用readonly
on type
。另一个好处是它不再需要type
Utility函数来强制转换字符串的类型。
完整代码在这里。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句