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

leveraging Ajax to submit a segment of the webpage

-Modified- Greetings, I am facing a situation where I need to post only the second form on a page that contains two forms. The second form has a function for validating data such as date, email, etc. My goal is to send the second form without reloading ...

Ensure that the form is validated when the radio buttons belonging to an unfamiliar group are

Looking to implement form validation that only triggers when all group radio buttons are checked. The challenge is making this dynamic as the number of radio button groups may vary. Is there a way to determine the number of groups in a form? This functio ...

A guide on updating data with duplicate values in Knex

Suppose I have the following array of data: const customerIds = [ '7d8206d2-74bc-4b90-a237-37f92486cde4', 'e594fe7f-d529-4a2f-ab24-ffc4e102268c', '7d8206d2-74bc-4b90-a237-37f92486cde4' ] As seen, there are duplicate IDs ...

Searching by multiple parameters in Angular.js

I have a script that scans through a field and highlights the words related to the search input. I want this script to not only filter by title, but also by name. How can I adjust the code to filter both the title and name when searching? <li ng-repeat ...

Should you consider using the Singleton pattern in Node.js applications?

After stumbling upon this specific piece discussing the creation of a singleton in Node.js, it got me thinking. The require functionality according to the official documentation states that: Modules are cached after the first time they are loaded. Multi ...

Leveraging async/await in express

I am encountering an issue with my app.post method while trying to deploy on Firebase. The error message reads: Parsing error: Unexpected token =>. I am fairly new to node.js and Javascript as I primarily work with Swift. However, I require this code fo ...

An express error caught off guard: Unexpected "write after end" issue detected

My current goal is to create a proxy for an api call from the client side through my server for a third party service. The main reasons for implementing this proxy are due to CORS issues and the need to include a secret key on the server side for added sec ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

Internet Explorer 11 Ajax problem

Once again, Internet Explorer is causing some issues. I have a file called validation.php where the values from a text box are sent for validation. The text box value is read and then a result indicates whether it is valid or not. This functionality work ...

Setting radio button values according to dropdown selection - a beginner's guide

I am trying to dynamically set the default values of radio buttons based on the selection made in a drop-down menu. For example, if option A or B is chosen, I want the radio button value to default to "Summary", and if option C is chosen, I want the value ...

Issue: The function _lib_getAllUsers__WEBPACK_IMPORTED_MODULE_2___default(...) is not recognized as a valid function

I'm currently following the YouTube series on Next.js by Dave Gray. My goal is to import a function from the file "lib/getAllUsers" https://i.sstatic.net/1SQMg.png However, I'm encountering the following error: Unhandled Runtime Error Error: ...

Updating the configuration settings for CKEditor 5 using Reactjs

I followed the configuration provided in another answer at But, I am facing an issue: Failed to compile. ./src/components/cards/CreateCard.js Line 59:22: Parsing error: Unexpected token, expected "}" 57 | editor={ClassicEditor} 58 | ...

Having trouble finding the correct output when searching in the table using regex

I am currently experiencing an issue with my code for searching. When I search the full text, it works fine but when I search for a middle character, it does not work as expected. For instance, searching for "apple" or "ap" works correctly, however, if I ...

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

What is the best method to prevent next.js components from overlapping one another?

I recently created a website using next.js and noticed an issue in my index.js file. There is a div that houses the main components of the site: class Page extends Component { render() { return ( <div className={styles.container}> ...

Steps for combining two collections into a single output in MongoDB with Node.js

My MongoDB collections consist of data that I need to merge using the $lookup operation. However, the result I get contains a nested array structure that is not ideal. I am looking for a solution to format the result as shown below: First collection locati ...

How can I efficiently transfer information between AngularJS modules?

Angular offers the flexibility of creating independent Modules that can be reused in various parts of your application. Imagine having a module dedicated to managing lists, which you want to use across your entire application and populate in different ways ...

Highlight all text in the textbox upon selection

I discovered a helpful script on how to select all contents of a textbox when it receives focus using JavaScript or jQuery. My attempt to implement this in IE10 revealed that the focus was being cleared at a later time, and my efforts to prevent this (whi ...

Adjust the width of a container to exceed 32767 using jquery in the Opera browser

I am looking to create a compact timeline using jQuery, and I want this timeline to have a width exceeding 32767 pixels. Interestingly, when I attempt to modify the width using the jQuery code $(".timelinecontainer").width(32767);, it doesn't seem to ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...