Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

angular - Getting error while registering reducers using ActionReducerMap: "not&#160;assignable&#160;to&#160;type&#160;'ActionReducerMap<AppState,&#160;Action>"

Below is simplified version of my Angular 5 application. I have a reducer, which I want to register in my root module. In LINE A I am getting following error:

ERROR in src/app/store/app.reducers.ts(7,14): error TS2322: Type '{ post: (state: State, action: Action) => void; }' is not assignable to type 'ActionReducerMap<AppState, Action>'.
  Types of property 'post' are incompatible.
    Type '(state: State, action: Action) => void' is not assignable to type 'ActionReducer<State, Action>'.
      Type 'void' is not assignable to type 'State'.

app.module.ts : Root module

  imports: [
    ...
    StoreModule.forRoot(reducers)
  ],

store/app.reducers.ts : inside Global store

import {ActionReducerMap} from "@ngrx/store";
import * as fromPost from "../postDir/store/post.reducers";

export interface AppState {
  post:fromPost.State
}
export const reducers: ActionReducerMap<AppState> = { //=======LINE A ======
  post:fromPost.postReducer
};

postDir/store/post.reducers.ts :inside local store

export interface State{
  query:string
  posts:Post[]
}

const initialPostState: State = {
  query:"initial",
  posts:[]
};

export function postReducer(state = initialPostState, action:postActions.PostActions){}

Code works fine if I replace <AppState> in LINE A with <any> Did anyone else face the similar issue? I tried to google but could not find anything significant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your error message says that property post has the wrong method signature. It is (state: State, action: Action) => void, but should be (state: State, action: Action) => State.

In post.reducers.ts your reducer needs to return the state that is passed into it like this:

export function postReducer(state = initialPostState, action:Action) { 
  return state;
};

The return type is being implicitly inferred from what you are, or in this case aren't, returning.

You could explicitly state the return type with ...): State {... but you should still return the state.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...