Unable to generate a store using reducer in TypeScript and Redux

I am having trouble creating a store using Redux and TypeScript. Here is my actions.js file:

import { Action } from 'redux';

export interface ITodoAction extends Action {
    todo:string;
}

export const ADD_TODO:string = 'ADD_TODO';
export function addTodo(todo:string):ITodoAction {
    return {
        type: ADD_TODO,
        todo
    };
}

I have exported an interface for a custom action named ITodoAction, which extends Action to include my custom property "todo.".

Now moving on to reducers.js:

import { Reducer } from 'redux';
import { ITodo } from '../interfaces';
import { ITodoAction, ADD_TODO } from '../actions';

let id:number = 0;
const generateId = ():number => id++;

interface ITodoState {
    todos:Array<ITodo>
};

const defaultState:ITodoState = {
    todos: []
};

export function todoReducer(state:ITodoState = defaultState, action:ITodoAction):ITodoState {
    switch(action.type) {
        case ADD_TODO:
            return Object.assign({}, state, {
                todos: [
                    { id: generateId(), text: action.todo, completed: false },
                    ...state.todos
                ]
            });
        default:
            return state;
    }
}

I have utilized ITodoAction from the previous actions.js file to define the todoReducer. The todoReducer returns an instance of ITodoState, which looks like this:

{
   type: 'ADD_TODO',
   todos: [ ITodo{}, ITodo{}, ITodo{}, ... ]
}

This is the ITodo interface that I used:

export interface ITodo {
    id:number;
    todo:string;
    completed:boolean;
}

It is a simple object containing properties for id, text, and completed. However, when I attempted to create a store with the reducer as shown below, it failed:

import { createStore } from 'redux';
import todoReducer from './reducers';

export const store = createStore(todoReducer);

The error message states:

Argument of type 'typeof "/.../typescript-todo/src/ts/reducers/index"' is not assignable to parameter of type 'Reducer<{}>'...
Type 'typeof "/./typescript-todo/src/ts/reducers/index"' provides no match for the signature '&lt;A extends Action&gt;(state: {}, action: A): {}'

It seems that I need to fix my reducer, but I am unsure how to define it with Reducer<{}>. Every attempt I made resulted in similar errors. Why can't I simply use my basic reducer?

I came across numerous posts related to TypeScript and Redux, but they did not use Reducer<{}> or Action>T<. This has left me confused as to why they worked without these interfaces.

Upon further research, I found the type declaration of Redux and discovered what Reducer<{}> looks like:

export type Reducer<S> = <A extends Action>(state: S, action: A) => S;

My understanding is that Reducer<{}> is a function that returns the state. So why does my todoReducer not work with them? I tried with Reducer<ITodoState>, but it still did not work.

I am extremely confused now and feel like I must be missing something significant. I never imagined that using Redux with TypeScript would be so challenging.

Despite my best efforts, I seem to require assistance. Any advice would be greatly appreciated.

Answer №1

Resolved the issue by simply exporting the reducer as default in the code, which successfully fixed it.

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

Ways to invoke a function in an angular component from a separate component located in a different .ts file

File3.ts export class3(){ method1(x,y){ .... } } File4.ts export class4(){ a: string = "abc" b: string ="xyz" //How can I call method1 and pass parameters from file 3? method1(x,y); } I attempted the following in Fi ...

Displaying object properties in React and rendering them on the user interface

Within my React application, I am retrieving data from an API using the following code snippet: function PlayerPage() { interface PlayerDataType { id: number; handle: string; role: string; avatar: string; specialAbilities: null; s ...

Angular fails to retrieve the data from an Object

I have both backend and frontend applications. When I attempt to retrieve information about the 'Probe' object, I can see its fields: https://i.stack.imgur.com/TJQqI.png However, when I try to access this information in Angular, I receive an und ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

Leveraging Angular Firebase MatTable with the power of 2 observables in 1

I'm currently facing an issue with my Firebase database data structure where I have a reference to a user id. Here's an example of the original data in my collection: { city: new york, country: usa addedBy: feibf78UYV3e43 // This is the USER ID ...

Typescript issue when a value is possibly a function or null

I have defined a type called StateProps with the following properties type StateProps = { isPending: boolean, asyncFn: (...args: any[]) => void | null } To initialize, I set up an initialState variable where the asyncFn property is initially s ...

What is the process for including an extra track in Twilio Video?

Since updating the twilio-video JS SDK from version 1.x to 2.x, I've encountered an issue when trying to add an additional device. An example of the error message is as follows: ERROR TypeError: transceiver.sender.replaceTrack(...).then(...).finally i ...

a helpful utility type for extracting a union from a constant array of strings

I create string arrays using const assertions and then use them to generate union types. const elements = ["apple", "banana", "orange"] as const; type elementsUnion = typeof elements[number]; // type elementsUnion = "appl ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Model Mongoose TypeScript Interface Type

I am working with 2 models in my project import {model, Schema, Types} from 'mongoose' interface IResource { user : Types.ObjectId | IUsers, type : Types.ObjectId | IResourceData, value : number, lastUpdate : number | Date, ...

When working with Typescript, you can declare an interface and split its definition across multiple files

I've been developing a software application that utilizes WebSocket with the NodeJS ws package. My networking structure revolves around a module responsible for handling message reception and transmission. Given that I'm working with TypeScript, ...

I encountered an issue where I did not receive a response when utilizing res.write() within the fetch function

Currently, I am utilizing the <res.write()> method in nodejs at https://nodejs.org/api/http.html#responsewritechunk-encoding-callback. In addition to this, I am also implementing the fetch function which can be found at https://developer.mozilla.org/ ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

Prevent Component Reloading in Angular 4 when revisiting the page

My application consists of three main components: 1) Map 2) Search 3) User Profile Upon logging in, the MAP component is loaded by default. I can navigate to other screens using the header menu link. I am looking to implement a feature where the map comp ...

Troubleshooting issue of incorporating hintText in a TextField within a create-react-app-with-typescript

After recently downloading, installing, and running the create-react-app-with-typescript, I have been exploring different components. My latest experiment involved adding a TextField with hintText using the following code: import TextField from 'mate ...

Is there a specific instance where it would be more appropriate to utilize the styled API for styling as opposed to the sx prop in Material-

I am currently in the process of migrating an existing codebase to Material UI and am working towards establishing a styling standard for our components moving forward. In a previous project, all components were styled using the sx prop without encounteri ...

What could be the reason for the variable's type being undefined in typescript?

After declaring the data type of a variable in TypeScript and checking its type, it may show as undefined if not initialized. For example: var a:number; console.log(a); However, if you initialize the variable with some data, then the type will be display ...

Converting an Array of Objects into a single Object in React: A Tutorial

AccessData fetching information from the database using graphql { id: '', name: '', regions: [ { id: '', name: '', districts: [ { id: '', ...