Angular NgRx 类型检查 app.reducer.ts 错误

Angular NgRx type checking in app.reducer.ts errors

我有一个简单的login/logout状态管理。 我收到此错误:

类型“(state: State | undefined, action: authActions) => State”不可分配给类型 'ActionReducer<State, Action>'。 参数类型 'action' 和 'action' 不兼容。 类型 'Action' 不可分配给类型 'authActions'。 类型 'Action' 不可分配给类型 'Logout'。 属性 'type' 的类型不兼容。 类型 'string' 不可分配给类型 'types.LOGOUT'.

这是我的文件。

auth.actions.ts

import { Action } from '@ngrx/store';
import { User } from '../user/user.model';

export enum types {
  LOGIN = '[AUTH] LOGIN',
  LOGOUT = '[AUTH] LOGOUT',
}

export class Login implements Action {
  readonly type = types.LOGIN;
  constructor(public payload: User) {}
}

export class Logout implements Action {
  readonly type = types.LOGOUT;
}

export type authActions = Login | Logout;

auth.reducer.ts

import { User } from '../user/user.model';
import * as authActions from './auth.actions';
export interface State {
  isLoggedIn: boolean;
  user: User | null;
}

const initialState: State = {
  isLoggedIn: false,
  user: null,
};

export function authReducer(
  state: State = initialState,
  action: authActions.authActions
): State {
  switch (action.type) {
    case authActions.types.LOGIN:
      return { ...state, isLoggedIn: true, user: action.payload };
    case authActions.types.LOGOUT:
      return { ...state, isLoggedIn: false, user: null };
    default:
      return state;
  }
}

app.reducer.ts

import { ActionReducerMap } from '@ngrx/store';
import * as fromAuthReducer from '../auth/store/auth.reducer';

export interface AppState {
  auth: fromAuthReducer.State;
}

export const appReducer: ActionReducerMap<AppState> = {
  auth: fromAuthReducer.authReducer,
};

这是使用 ngrx 旧语法的问题。您应该使用更好地支持打字稿的创建者语法。

您的代码的解决方案是使用 any ActionReducerMap 类型:

export const appReducer: ActionReducerMap<AppState, any> = {
  auth: fromAuthReducer.authReducer,
};