Omar Zahir
Omar Zahir

Reputation: 215

Angular NgRx type checking in app.reducer.ts errors

I have a simple login/logout state management. I get this error:

Type '(state: State | undefined, action: authActions) => State' is not assignable to type 'ActionReducer<State, Action>'. Types of parameters 'action' and 'action' are incompatible. Type 'Action' is not assignable to type 'authActions'. Type 'Action' is not assignable to type 'Logout'. Types of property 'type' are incompatible. Type 'string' is not assignable to type 'types.LOGOUT'.

Here are my files.

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,
};

Upvotes: 1

Views: 1787

Answers (1)

HTN
HTN

Reputation: 3594

It's the problem using the old syntax of ngrx. You should use the creator syntax which supports typescript better.

The solution for your code is using any type for ActionReducerMap:

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

Upvotes: 5

Related Questions