美好的一天。
我需要有关以下问题的帮助。不久前,我们更新了我们的项目以使用 Angular 12,我一直在尝试将 @ngrx/store 从 v10 更新到 v11(或 v12)。当我们还在使用 Angular 11 时,我确实尝试过此更新,但我不断收到此错误:
Argument of type 'ReducerTypes<unknown, [ActionCreator<"EnableForm", () => TypedAction<"EnableForm">>]>' is not assignable to parameter of type 'ReducerTypes<AppState, ActionCreator<string, Creator<any[], object>>[]>'.
Types of property 'reducer' are incompatible.
Type 'OnReducer<unknown, [ActionCreator<"EnableForm", () => TypedAction<"EnableForm">>]>' is not assignable to type 'OnReducer<AppState, ActionCreator<string, Creator<any[], object>>[]>'.
Type 'unknown' is not assignable to type 'AppState'.
我的减速器看起来像这样:
import { Action, createReducer, on } from '@ngrx/store';
import * as MyAction from '../actions';
import { AppState } from '../state';
import { onEnableForm, onDisableForm } from './form.reducer';
const initialState: AppState = {
form: {
disabled: false,
...
},
...
};
export function storeReducer(state: AppState = initialState, action: Action): AppState {
return createReducer<AppState>(
state,
on(MyAction.InitializeState, MyAction.ResetState, () => initialState),
on(MyAction.DestroyState, () => undefined),
onEnableForm,
onDisableForm
)(state, action);
}
actions.ts
看起来像这样:
import { createAction } from '@ngrx/store';
export const InitializeState = createAction('[MyFeatureStore] InitializeState');
export const ResetState = createAction('[MyFeatureStore] ResetState');
export const DestroyState = createAction('[MyFeatureStore] DestroyState');
export const EnableForm = createAction('[MyFeatureStore] EnableForm');
export const DisableForm = createAction('[MyFeatureStore] DisableForm');
form.reducer.ts
看起来像这样:
import { on } from '@ngrx/store';
import * as MyAction from '../actions';
import { AppState } from '../state';
export const onEnableForm = on(MyAction.EnableForm, (state: AppState) => {
return {
...state,
form: {
...state.form,
disabled: false
}
};
});
export const onDisableForm = on(MyAction.DisableForm, (state: AppState) => {
return {
...state,
form: {
...state.form,
disabled: true
}
};
});
这在 v10 中可以正常工作,但我不明白为什么它在 v11 中不起作用。
答案 0 :(得分:3)
正在发生的事情是 angular 和所有打字稿世界都在转向越来越强类型的规则,因此当您在管道外创建 on
函数时,打字稿无法推断发生了什么。
您可以做的是像这样扩展 on
函数的类型
export const onEnableForm = on<AppState, any>(EnableForm, (state: AppState): AppState => {
return {
...state,
form: {
...state.form,
disabled: false,
}
};
});
export const onDisableForm = on<AppState, any>(
DisableForm,
(state: AppState): AppState => {
return {
...state,
form: {
...state.form,
disabled: true
}
};
}
);
您可以将其用作解决方法,直到您找到要使用的适当类型而不是 any
。这是带有建议解决方案的 stackblitz。