Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing?

'IinitialAssetsState' is not assignable to type 'Reducer'

The complete error message:

Type '(state: { assets: never[]; portfolio: never[]; loading: boolean; } | undefined, action: any) => IinitialAssetsState' is not assignable to type 'Reducer'.

Types of parameters 'state' and 'state' are incompatible.

Type 'IinitialAssetsState | undefined' is not assignable to type '{ assets: never[]; portfolio: never[]; loading: boolean; } | undefined'.

Type 'IinitialAssetsState' is not assignable to type '{ assets: never[]; portfolio: never[]; loading: boolean; }'.

Types of property 'assets' are incompatible.

Type 'IAsset[]' is not assignable to type 'never[]'.

Type 'IAsset' is not assignable to type 'never'.

https://i.stack.imgur.com/90WA8.png

My store.ts file

import { applyMiddleware, createStore, combineReducers } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'

import { IinitialState } from './shared/types'
import { AssetsReducer } from './reducers/assets'
import { BoardReducer } from './reducers/board'

const rootReducer = combineReducers({
  AssetsReducer,
  BoardReducer
});

export const defaultInitialState = {
  AssetsReducer: { assets: [], loading: false, portfolio: [] },
  BoardReducer: { overlay: false },
}

export function initializeStore(initialState: IinitialState = defaultInitialState) {
  return createStore(
    rootReducer,
    initialState,
    composeWithDevTools(applyMiddleware(thunkMiddleware))
  )
}

AssetsReducer

import { Actions } from '../actions/assets'
import { IinitialAssetsState } from '../shared/types'

const defaultAssetsState = { assets: [], portfolio: [], loading: false };

export const AssetsReducer = (state = defaultAssetsState, action: any): IinitialAssetsState => {
  switch (action.type) {
    case Actions.GET_ALL_ASSETS: {
      const { assets } = action;
      return {
        ...state,
        assets,
        loading: false
      };
    }

    default:
      return state;
  }
};

BoardReducer

import { Actions } from '../actions/board'
import { IinitalBoardState } from '../shared/types'

const defaultBoardState = { overlay: false };

export const BoardReducer = (state = defaultBoardState, action: any): IinitalBoardState => {
  switch (action.type) {
    case Actions.SET_OVERLAY_STATE: {
      const { overlay } = action;
      return {
        overlay
      };
    }

    default:
      return state;
  }
};

My types file

export interface IAsset {
  position: number;
  marketCap: number;
  name: string;
  percentage: number;
  price: number;
  currency: string;
  value: number;
}

export interface IinitialAssetsState {
  assets: IAsset[];
  portfolio: IAsset[];
  loading: boolean;
}

export interface IinitalBoardState {
  overlay: boolean;
}

export interface IinitialState {
  AssetsReducer: IinitialAssetsState;
  BoardReducer: IinitalBoardState;
}

What I've attempted

I defined a type for the action to eliminate the usage of any, but I am still encountering the same Typescript error:

interface IAssetsAction {
  type: string;
  assets: IAsset[];
}

export const AssetsReducer = (state = defaultAssetsState, action: IAssetsAction): IinitialAssetsState => {
  console.log('action', action);
  switch (action.type) {
    case Actions.GET_ALL_ASSETS: {
      const { assets } = action;
      return {
        ...state,
        assets,
        loading: false
      };
    }

Answer №1

I suspect the issue lies within the store.ts file:

export const defaultInitialState = {
  AssetsReducer: { assets: [], loading: false, portfolio: [] },
  BoardReducer: { overlay: false },
}

In this code snippet, the defaultInitialState.assets is assigned as type never[].

To resolve this, you must define the type for defaultInitialState.

export const defaultInitialState : IinitialState  = {
  AssetsReducer: { assets: [], loading: false, portfolio: [] },
  BoardReducer: { overlay: false },
}

Furthermore, don't forget to update the types in AssetsReducer and BoardReducer

const defaultBoardState : IinitalBoardState = { overlay: false };

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

Transitioning from the traditional LeftNav menu style to the more versatile composability feature using Reactjs with Material-ui

Hey there, I'm facing a bit of confusion while trying to create a LeftNav menu using material-ui. I recently joined this project and updated reactjs and material-ui. Unfortunately, many things related to LeftNav in material-ui have been deprecated, ...

Tips for transferring the id from the url to a php function seamlessly without causing a page refresh

I have a div that includes a button (Book it). When the button is clicked, I want to append the id of the item I clicked on to the current URL. Then, use that id to display a popup box with the details of the clicked item without refreshing the page, as it ...

Experiencing a problem in React JS when trying to render a component?

I encountered an error message while trying to render a component from an object. Type 'FC<Boxprops> | ExoticComponent<{ children?: ReactNode; }>' is not compatible with type 'FC<Boxprops>'. Type 'ExoticComponen ...

Creating a collapsible accordion feature with jQuery using a specific HTML layout: wanna learn how?

I am looking to create an accordion effect with the structure provided below. The goal is to have the corresponding article toggle when clicking on .booklist>li>a, allowing only one article to be open at a time. Can someone assist me with writing this scri ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

When the JS function 'postMessage()' is invoked on an HTML object tag, what specific action does it perform?

Not too long ago, I found myself on a quest to figure out how to trigger the print function on a PDF that I was displaying in Adobe AIR. With a bit of guidance from a helpful individual and by utilizing postMessage, I successfully tackled this issue: // H ...

The Concept of Interface Segregation Principle within jQuery

Could someone provide a clear explanation of how this function operates using jQuery? Especially in reference to the response found here. It seems similar to the Single Responsibility Principle (SRP) in Object-Oriented Programming. What sets it apart? ...

Retrieve JSON object by matching another JSON property

I am working with an array of id's and their respective contents in a JSON response. My goal is to retrieve the content based on the received id. For instance, if the ID is 1 (returned from the JSON), I aim to access the JSON data using "data.id" (wh ...

How come TinyMCE is showing HTML code instead of formatted text?

I have been working on integrating TinyMCE with React on the frontend and django(DRF) on the backend. After saving data from TinyMCE, it retains the HTML tags when displayed back, like this: <p>test</p> <div>Test inside div</div> ...

Retrieve all users along with their respective posts, ensuring that each post is also accompanied by its corresponding comments in

In my Laravel project, I have set up Eloquent models for User, Post, and Comment. The relationships are as follows: User model public function posts(){ return $this->hasMany('App\Post'); } public function comments(){ return $t ...

Invoke the identical function in between two functions that make asynchronous AJAX calls

I seem to be a little lost at the moment. The code snippet below illustrates my intent, which is to use the insertChilds() function to insert child elements in the DOM in a cascading manner (or at least that's what I'm aiming for...). The challe ...

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Leveraging shadow components with the Next.js pages directory

I am facing an issue with getting a simple shadcn button to work because I am unable to import the button. Although I am using nextjs 13, I am still utilizing the pages directory. Below is the process of how I installed shadcn. Here is the installation co ...

What is the best way to embed two controllers within an AngularJS webpage?

Currently, I have a Web Forms ASP.NET website that I am trying to enhance by adding an AngularJS page. This page is meant to interact with my RESTful Web API to display quotes for selected securities upon button click. While the Web API calls work when dir ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

How to achieve the functionality of multiple inheritance using Object.create()

Seeking insights on implementing multiple inheritance in JavaScript. Various methods exist, each with pros and cons. However, there lacks a comprehensive analysis of Object.create() presented in an understandable manner. After conducting experiments, I hav ...

Simulating Cordova plugin functionality during unit testing

I have a code snippet that I need to test in my controller: $scope.fbLogin = function() { console.log('Start FB login'); facebookConnectPlugin.login(["public_profile", "email", "user_friends"], FacebookServices.fbLoginSuccess, FacebookServic ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...

The error was thrown at line 800 in the loader.js file of the internal modules

When I ran yarn install in my project folder, I encountered the following error: internal/modules/cjs/loader.js:800 throw err; ^ Error: Cannot find module 'ts-node/register' Require stack: - internal/preload ?[90m at Function.Module._resolveF ...

Implementing jQuery to trigger actions on every other click

Here we have a snippet of code that either posts and updates #arrival or removes it and replaces it with standard text. One click for posting, another click to reset. The issue is that currently it requires two clicks to do the initial posting, followed by ...