@ngrx/store 从 v10 更新到 v11 / v12

@ngrx/store update from v10 to v11 / v12

美好的一天。

我需要帮助解决以下问题。不久前,我们将项目更新为使用 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 中不工作。

正在发生的事情是 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 和建议的解决方案。