Search code examples
angularangular7ngrx-store

ngrx store Combine Reducer throw error as ` error TS2322: Type 'ActionReducer<{}, Action>' is not assignable`


I am using ngrx, and trying to combine 2 reducers. getting error as

ERROR in src/app/state/index.ts(17,7): error TS2322: Type 'ActionReducer<{}, Action>' is not assignable to type 'ActionReducer<AppState, Action>'.
  Type '{}' is missing the following properties from type 'AppState': count, title

not able to understand. how to fix this?

here is my code : where i am getting error.

import { combineReducers, ActionReducer } from '@ngrx/store';
import { compose } from '@ngrx/core/compose';
import { storeFreeze } from 'ngrx-store-freeze';


import { reducerCount } from "./reducerCount";
import { reducerTitle } from "./reducerTitle";
import { AppState } from "./../models/State";

const reducers = {
    redCount : reducerCount,
    redTitle : reducerTitle
}


const developmentReducer: ActionReducer<AppState> = compose(storeFreeze, combineReducers)(reducers); //throws error here

export function reducer(state: any, action: any) {
  return developmentReducer(state, action);
}

here is my AppState:

import { TitleState } from "./TitleState";//has model
import { CounterState } from "./CouterState";//has model

export interface AppState {
    count : CounterState;
    title : TitleState;
}

TitleState.ts
    export interface CounterState {
        counter:number
    }
CouterState.ts    
    export interface TitleState {
        title:string;
    }

here is my reducers:

    export function reducerCount(state=0, action) {
        switch (action.type) {
            case "INCREMENT":
                return state + 1;

            case "DECREMENT":
                return state - 1;

            default:
                return state;
        }
    }


const basicValues = {
    title:"ABC"
}

export function reducerTitle(state=basicValues, action) {
    switch (action.type) {
        case "UPDATE_TITLE":
            return {
                ...state,
                title:"TCH"
            }

        default:
            return state;
    }
}

Live Demo here => please check in the state -> index.ts


Solution

  • You AppState shape doesn't mach the State's peaces you provide in combineReducers(). Replase:

    export interface AppState {
        counter : CounterState;
        title : TitleState;
    }
    

    Into:

    export interface AppState {
        countReducer : CounterState;
        titleReducer : TitleState;
    }
    

    And to note - combineReducers() in NGRX is being used implicitly when you set StoreModule.forRoot() and StoreModule.forFeature()