Error in Type definition of action.payload in Typescript Redux Slice module

I am encountering an issue when trying to add a type to action.payload in the Redux Toolkit.

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface InputState {
  user: {
    firstName: string;
    lastName: string | null;
    userID: number | null;
  };
}

const initialState: InputState = {
  user: {
    firstName: "individual",
    lastName: null,
    userID: null,
  },
};

export const inputsDataSlice = createSlice({
  name: "inputsData",
  initialState,
  reducers: {
    setValue: (state, action: PayloadAction<string | number | null>) => {
      const data: string = action.payload;

      switch (data.id) {
        case "firstName":
          return void (state.user.firstName = data.value);
        case "lastName":
          return void (state.user.lastName = data.value);
        case "userID":
          return void (state.user.userID = data.value);
        default:
          return;
      }
    },
  },
});

export const { setValue } = inputsDataSlice.actions;
export default inputsDataSlice.reducer;

The error message 'Property 'value' / 'id' does not exist on type 'string'' is still appearing for data.id and data.value. I have specified the types as <string | number | null> with PayloadAction, so where could the mistake be located?

If you could provide any guidance on this issue, it would be greatly appreciated. Thank you!

Answer №1

It is up to you to define

let info: string = action.payload;

Furthermore, using <string | number | null> implies that action.payload can be either a string, number, or null, and not the sub-property value of action.payload, as you are trying to access through data.value

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

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

Using two indexes in ngFor can result in unexpected changes to the values being displayed

I am currently working on printing checkboxes and facing an issue with initializing the id and name attributes using ngFor. The values I'm getting are incorrect. Let's consider 2 arrays (or n arrays retrieved from a database): animal = 'do ...

Ways to include a link/href in HTML using a global constants file

I have a constants file with a links node that I need to integrate into my HTML or TypeScript file. Constants File export const GlobalConstants = { links: { classicAO: '../MicroUIs/' } } I created a public method called backToClassicAO ...

Building a customizable class from scratch

I am currently working on developing configurable classes that come with default values, but allow for configuration changes if needed. The concept involves creating an instance of a class by calling its type specified in the static properties of the Test ...

Testing the addition of a dynamic class to an HTML button using Jasmine unit tests

I am brand new to Jasmine and currently in the process of grasping how to write Unit tests for my components in Angular 4. One issue I encountered is when I attempt to add a class to the button's classList within the ngOnInit() lifecycle hook of the C ...

Intellisense not working with express

After using the command npm install --save @types/express to install, I imported in my ts file as follows: import * as express from "express"; var app = express(); Despite this setup, I am not able to get intelisense on the app variable. Additionally ...

Validating TypeScript enum indexes

Take a look at the following code snippet: export enum ResponseCodes { 'Network error' = 5003 } const code: ResponseCodes = 4000 // This does not result in an error Even though the specified key is not present in the enum, why does it not ...

Having trouble editing a form with React Hooks and Redux?

Seeking assistance with creating an edit form in React that utilizes data stored in Redux. The current form I have created is displaying the values correctly, but it appears to be read-only as no changes are being reflected when input is altered. Any advic ...

Encountering a 504 Gateway Timeout error while attempting to send a POST request to an API route in a NEXT.JS application that

I encountered a 504 error gateway timeout when attempting to post a request to api/webhooks, and in the Vercel log, I received a Task timed out after 10.02 seconds message. This code represents a webhook connection between my clerk and MongoDB. [POST] [m ...

Tips for receiving a linter/compiler warning when comparing a function without its call being made?

Often, I find myself making a common mistake when writing TypeScript code: class Foo { constructor() { } public get isFoo(): boolean { return true; } // getter public isBar(): boolean { return false; } // normal function } let foo = new Foo(); if ( ...

Discover the Category of Union based on Discriminator

Imagine a scenario where there is a concept of a union type called Thing, which combines types Foo, Bar, and Baz, each identified by the property tag. interface Foo { tag: 'Foo' foo: string } interface Bar { tag: 'Bar' bar: nu ...

I keep encountering the message 'Invalid type of argument: string cannot be assigned to a parameter of type never' within the useNavigationBuilder.tsx file. What could be causing this issue?

if (route?.name) { routeNames.push(route.name); } } else { route = state.routes[state.index]; routeNames.push( ...Object.keys(screens).filter((name) => route?.name === name) ); } An unexpected error has ...

Is it possible to navigate within a React-Router V4 application without being in a React environment?

Currently, I am creating an app that utilizes two libraries in addition to React. Specifically, I am implementing Leaflet and Marzipano. For data synchronization, I have incorporated Redux into my project. One challenge I am facing is changing the route ...

Enhance your text in TextInput by incorporating newline characters with advanced editing features

I'm encountering an issue with my Textarea component that handles Markdown headers: type TextareaProps = { initValue: string; style?: StyleProp<TextStyle>; onChange?: (value: string) => void; }; type OnChangeFun = NativeSynthetic ...

Creating a dynamic horizontal list of buttons in NativeScript

I am currently diving into the world of NativeScript and I find myself struggling a bit with the MVVM concept, specifically when it comes to binding. I have configured my environment to work with TypeScript. On my HomePage, I am tasked with creating a hor ...

Ways to sidestep the rules set forth by tslint

Currently, I am facing an issue where I need a specific class to disable the max-classes-per-file restriction. I attempted to add the rule /* tslint:disable:max-classes-per-file: */ to the beginning of the file, but I still received the warning. Even af ...

Implementing conditional wildcard route redirection in an Angular routing module

Is there a way to manage redirect routes when users enter the wrong URL using wildcards controlled by conditions? In my project, I have 3 main modules that are separate, and each of them has specific conditions for user access based on roles. The issue I ...

Tips for Achieving Observable Synchronization

I've encountered a coding challenge that has led me to this code snippet: ngOnInit(): void { this.categories = this.categoryService.getCategories(); var example = this.categories.flatMap((categor) => categor.map((categories) = ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

Struggling to successfully pass React props.children

Currently, I am utilizing react in my project and I have encountered an error when passing props.children to the Header component. Despite passing React as the type, the following error message is displayed. I am unsure why this error is happening. e ...