What could be causing TypeScript to throw errors regarding the initialState type when defining redux slices with createSlice in reduxToolkit, despite it being the correct type specified?

Here is my implementation of the createSlice() function:

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

type TransferDeckModeType = "pipetting" | "evaluation" | "editing";

var initialState: TransferDeckModeType = "pipetting";

const transfer_deck_mode = createSlice({
  name: "transfer_deck_mode",
  initialState,
  reducers: {
    setTransferDeckMode(state, action: PayloadAction<TransferDeckModeType>) {
      let newState = action.payload;
      return newState;
    },
  },
});

export const { setTransferDeckMode } = transfer_deck_mode.actions;

export default transfer_deck_mode.reducer;

An issue arises with the setTransferDeckMode function in Typescript.

Type '(state: "pipetting", action: { payload: TransferDeckModeType; type: string; }) => TransferDeckModeType' is not assignable to type 'CaseReducer<"pipetting", { payload: any; type: string; }> | CaseReducerWithPrepare<"pipetting", PayloadAction<any, string, any, any>>'.
  Type '(state: "pipetting", action: { payload: TransferDeckModeType; type: string; }) => TransferDeckModeType' is not assignable to type 'CaseReducer<"pipetting", { payload: any; type: string; }>'.
    Type 'TransferDeckModeType' is not assignable to type 'void | "pipetting"'.
      Type '"evaluation"' is not assignable to type 'void | "pipetting"'.ts(2322)
(method) setTransferDeckMode(state: "pipetting", action: PayloadAction<TransferDeckModeType>): TransferDeckModeType

The unexpected presence of 'void' raises questions about the state declaration. What is introducing 'void' and setting it alongside ""pipetting""? It's puzzling as the state should not be void in this context.

There seems to be confusion on where to specify the state of the slice. Shouldn't it be inferred from the type of initialState? This oversight is causing confusion.

Interestingly, changing the type of initialState to string resolves the error.


var initialState: string = "pipetting";

However, this solution feels inadequate. Why can't I define the type of the initialState directly?

Answer №1

This is the exact reason why the RTK documentation displays

var initialState = "pipetting" as TransferDeckModeType ;

instead.

With TypeScript conducting flow analysis in this scenario, you have the opportunity to test it out on this TypeScript Playground

function something<T>(initialState: T) { return { initialState } }
type Values = 'a' | 'b'

{
var initialState: Values = 'a';
//    ^?

const derivedValue = something(initialState)
//    ^?
// Through flow analysis, TS considers `initialState` as `'a'`
// and associates `derivedValue` with `{ initialState: "a" }`
}

{
var initialState = 'a' as Values;
//    ^?

const derivedValue = something(initialState)
//    ^?
// In this scenario, a type assertion could prevent that,
// instructing TS to not be overly intelligent
}

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

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

React component state remains static despite user input

I am currently in the process of developing a basic login/signup form using React, Typescript (which is new to me), and AntDesign. Below is the code for my component: import React, { Component } from 'react' import { Typography, Form, Input, But ...

How can a class be imported into a Firebase Cloud function in order to reduce cold start time?

When optimizing cold start time for Firebase Cloud functions, it is recommended in this Firebase Tutorial to import modules only where necessary. But can you also import a class with its own dependencies inside a function? In my scenario, I need to use Bc ...

Implementing recursive functionality in a React component responsible for rendering a dynamic form

Hello to all members of the Stack Overflow community! Presently, I am in the process of creating a dynamic form that adapts based on the object provided, and it seems to handle various scenarios effectively. However, when dealing with a nested objec ...

Utilizing the dialogue feature within Angular 6

Situation: I am managing two sets of data in JSON format named customers and workers: customers: [ { "cusId": "01", "customerName": "Customer One", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

How can I add a new key value pair to an existing object in Angular?

I'm looking to add a new key value pair to an existing object without declaring it inside the initial object declaration. I attempted the code below, but encountered the following error: Property 'specialty' does not exist on type saveFor ...

What is the best way to bundle a TypeScript package along with its dependencies for seamless integration with various Next.js projects on a local environment

Currently, I am immersed in a project with the following arrangement: / # repository root /core # A local, unpublished npm package used by both projectA and projectB /projectA # A Next.js app /projectB # Another Next.js app In my setup, I gene ...

How to use attributes in Angular 2 when initializing a class constructor

Is there a way to transfer attributes from a parent component to the constructor of their child components in Angular 2? The process is halfway solved, with attributes being successfully passed to the view. /client/app.ts import {Component, View, bootst ...

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...

activating serverless.yml for aws-xray

I have been attempting to implement AWS X-Ray for all lambda functions in the following manner: serverless.yml provider: tracing: lambda: true apiGateway: true name: aws runtime: nodejs8.10 stage: ${opt:stage, 'dev'} region: ...

Tips on personalizing the formatting alert in Webclipse for Angular 2 using Typescript

Webclipse offers extensive formatting warnings for TypeScript code, such as detecting blank spaces and suggesting the use of single quotes over double quotes. However, some users find the recommendation to use single quotes annoying, as using double quotes ...

SonarLint versus SonarTS: A Comparison of Code Quality Tools

I'm feeling pretty lost when it comes to understanding the difference between SonarLint and SonarTS. I've been using SonarLint in Visual Studio, but now my client wants me to switch to the SonarTS plugin. SonarLint is for analyzing overall pr ...

Encountering difficulties with installing bootstrap-vue

While attempting to integrate Bootstrap-Vue into my project that includes Vuex, Vue-Router, TypeScript, and Babel, I encounter an error in the browser. To replicate docker run -it --rm -p 8080:8080 node:17.7.2-alpine yarn global add @vue/cli vue create ...

Link the Angular Material Table to a basic array

Currently facing a challenge with the Angular Material table implementation. Struggling to comprehend everything... I am looking to link my AngularApp with a robot that sends me information in a "datas" array. To display my array, I utilized the following ...

Encountering a Typescript error when trying to invoke a redux action

I have created a redux action to show an alert message export const showAlertConfirm = (msg) => (dispatch) => { dispatch({ type: SHOW_ALERT_CONFIRM, payload: { title: msg.title, body: msg.body, ...

TypeScript encounters difficulty locating the div element

Recently attempted an Angular demo and encountered an error related to [ts] not being able to locate a div element. import { Component } from "@angular/core"; import { FormControl } from "@angular/forms"; @Component({ selector: "main", template: ' ...

I encountered a function overload error while creating a component for the API service

As a developer venturing into API design with a backend server that handles client-side calls, I find myself grappling with Typescript, transitioning from a Java background. Encountering the error message "No overload matches this call" has left me seeking ...