我有许多ngrx动作,它们具有共同的属性choice
:
export const actionA = createAction('a', props<{oneProperty: number, choice: boolean}>());
export const actionB = createAction('b', props<{anotherProperty: string, choice: boolean}>());
export const actionC = createAction('c', props<{choice: boolean}>());
我想在我的组件中引用此属性,例如:
constructor(private actions$: Actions) {
actions$.pipe(filter(action => action.choice)).subscribe(...
}
但是,天真地导致类型错误,因为actions$
是Observable<Action>
,而泛型Action
并不了解choice
。如果只有这样的两个动作,我可以使用ofType来缩小类型,如:
actions$.pipe(ofType('a', 'b'), filter(action => (<choice: boolean>action).choice))
如此处所示,“操作”的类型为ActionA|ActionB
。但是,我有许多此类操作,因此无法在此处进行硬编码。我尝试传递如下操作列表:
const actionList = ['a', 'b'];
actions$.pipe(ofType(...actionList), filter(action => (<choice: boolean>action).choice))
但是ofType(...allowedTypes)
不允许推理。该文档还说:
Type narrowing automatically works, as long as your actions object starts with a Actions<SomeUnionOfActions> instead of generic Actions.
我试图通过以下方式使Actions
成为联盟:
constructor(private actions$: Actions<typeof actionA>)
但是没有输入。我也尝试过Actions<{choice: boolean}>
,但是也没有输入。
如何在Actions
效果中使用我所有动作的共有属性,而又不在那里对它们的所有名称进行硬编码?