Encountering an issue during the registration of reducers with ActionReducerMap: "does not match the type 'ActionReducerMap<AppState, Action>'"

Here is a simplified version of my Angular 5 application. I have a reducer that needs to be registered in the root module. The problem arises in LINE A where I encounter the 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){}

If I replace <AppState> with <any> in LINE A, the code works fine. Has anyone else encountered this issue? I have tried searching online but couldn't find any significant solutions.

Answer №1

The error message you received indicates that the property post has an incorrect method signature. It currently reads as

(state: State, action: Action) => void
, but it should be
(state: State, action: Action) => State
.

Within the file post.reducers.ts, your reducer must return the state that was passed to it, like so:

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

The return type is implicitly inferred based on what you are returning, or in this case, not returning.

If desired, you can explicitly specify the return type with ...): State {..., but again, ensure that you are still returning the state.

Answer №2

Visit the tsconfig.json file and set strict to false.

Answer №3

In a similar situation, I encountered a problem that took me a lot of time to resolve. After thoroughly checking my code, I realized that there was a missing property return in the switch case actions within the reducer. It is important to make sure you load your previous state using the spread operator ...state to avoid encountering difficult-to-spot problems. In my case, I neglected to first load the previous state before returning all properties except one. This led to the TS2322 error and it took me hours to fix and comprehend what went wrong. You can use your code as a reference:

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

// Make sure to return the state after an action
   switch (action.type){
       case postActions.ACTION_EXAMPLE:
       return {
              ...state, someProperty: action.payload  // Load your previous state here and only change the necessary property

      }
      case postActions.ACTION_02_EXAMPLE:
      return {
              ...state, someProperty: action.payload  // Load your previous state here and only change the necessary property

      }
     default:
     return { ...state}
   } 
}

I hope this explanation proves useful!

Answer №4

Sharing a helpful tip for those facing a similar issue to one I encountered. In my case, while using @ngrx/entity, I needed to reset the state to its initial form upon a specific action. Initially, I had:

on(actions.resetState, () => adapter.getInitialState())

However, the correct approach involved including extra properties like this:

on(actions.resetState, () => adapter.getInitialState({ foo: 'bar' }))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for the array length view not updating when a new object is added?

I am dealing with an array of objects and the length is displayed using this code snippet: <strong *ngIf="cart">{{ cart.length }}</strong> Even though when I add items to the array, both the array and its length are showing correctly ...

The webpage is currently experiencing difficulty in displaying any information

As a beginner in React and typescript, I am working on a simple application that fetches data from an API and displays it on a web page. Despite fixing some errors and seeing the data in the console log, I am struggling to display any data on the actual we ...

"Utilizing a background image within a component to completely cover the entirety

Hey everyone, I need some help with a confusing issue. I'm currently working on an AngularJs project and I am struggling to set a background image for a specific component without affecting the entire application. My goal is to have the image cover t ...

What is the process for utilizing the TypeScript compiler with nodejs?

I have a sample code saved in a file called hello.ts Upon the completion of nodejs setup on Windows, execute the following command to install typescript: npm install -g typescript Is there a way to compile hello.ts directly with node.js? While using "T ...

Learn how to retrieve the index using PrimNG's TurboTable in conjunction with Angular version

Having trouble finding the correct way to display an index with Angular 6 and PrimeNG turbo table. This is what I have tried so far: <p-table [value]="timecards"> <ng-template pTemplate="body" let-timecard let-i="index"> <tr><t ...

Having trouble adding custom props to MUI-Material ListItemButtonProps? Facing a TypeScript error?

This particular task should be relatively straightforward. I am seeking a custom component that inherits all props from ListItemButtonProps, while also adding an extra state prop: type SidebarListItemButtonProps = ListItemButtonProps & { state: Sideb ...

Acquiring a second access token in Java for the Graph API using an OIDC-compliant token can be achieved through the OBO flow method

Utilizing the angular-oauth2-oidc library within Angular allows me to login through the PKCE Authorization Flow, followed by passing the token to my backend in order to secure my custom API. The Spring boot backend functions as the oauth2 Resource Server ...

What is the process for including a unique attribute for child elements within a React component using TypeScript?

I have a component that creates a Table of Contents (TOC) and List for the child elements. These children can be any JSX.Element. Here is an example... <SectionScrollList> <View key="first"/> <View key="second"/> ...

Selecting an option with a specific index in Angular 2 RC2

I have encountered a situation where the select options are non-unique, with the same value representing different things. This is how our data is structured and I need to work within those constraints. <select id="mySelect"> <option value = "1 ...

Having an issue with TypeScript and React where the onChange event on the <select> element is only setting the previous value instead of the current value when using the useState hook

I'm currently developing a scheduling web tool. One of the key features I'm working on involves calculating the total hours between two selected times, startTime and endTime. These times are chosen via a form and stored using the useState hook: ...

Dynamic rendering of independent routes is achieved by nesting a router-outlet within another router-outlet

I am working on an angular 2 project with multiple modules. To load each module, I am using the lazy loading technique in this way: { path: 'home', loadChildren: './dashboard/dashboard.module#DashboardModule' }, Currently, I am facing ...

Troubleshooting Shader Loading Issues in an Angular Application Utilizing Three.js

Check out this component: https://www.npmjs.com/package/app3d-three-template Here's the Plnkr link: https://plnkr.co/edit/bdkshJFzhwmLNdgO?preview The issue I'm facing is related to the fire Shader not displaying the correct color. Additionally ...

Experiencing difficulties with PrimeNg installation on Angular 12.1.4 due to an npm error

I'm facing an issue while trying to integrate PrimeNG into my project. I encountered a strange error and I'm unsure about how to resolve it. Can anyone offer some assistance? The Angular version currently installed on my machine is 12.1.4. 205-18 ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

Receiving intelligent suggestions for TypeScript interfaces declared within function parameters

Here is a simple example I put together: https://i.sstatic.net/Fdtfa.png In this example, intellisense provides suggestions for the interface of the object named test in the foo function. It works perfectly and I love it! However, if you declare that in ...

Leveraging the keyof keyword to access a specific property within a type

I have a variety of types that I need to work with. For example: type Type = { prop1: number; prop2: string; prop3: someOtherType } type Props = keyof Type I am aware that using an "indexed access type" allows me to extract the type of propN, ...

Angular2 allows for the firing of all columns in one click using *ngFor

<tr *ngFor = 'let student of students> <td contenteditable="true" class ='phone' #button> {{student.phone}} <i (click)='showbox()' class = ' glyphicon glyphicon-edit'></i> <input *ngIf=&apo ...

Showing or hiding elements based on user roles in Angular 4

I am currently working on a project that involves multiple user types (SuperUser - SchoolAdmin - Teacher). Each role has specific privileges to access certain elements. How can I dynamically hide elements based on the logged-in user's role using *ng ...

The tooltip popup does not appear within the nz-tabs

Looking to enhance my two tabs with an info icon preceding the tab text, along with a tooltip popup that appears when hovering over the icon. Despite trying different methods, I have yet to achieve the desired outcome. <nz-tabset [nzLinkRouter]=&qu ...

Best practices for implementing dual ngFor directives within a single tr element?

Click here to view the page The image attached shows the view I want to iterate through two ngFor loops inside the tr tag. When using a div tag inside the tr, it's looping the button next to the tag instead of where I want it in the file table header ...