question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Typescript infer state type incorrectly in createSlice's reducers

See original GitHub issue

Hello,

Problem Description:

For some reason, I’ve been using RTK createSlice as follow:

import { createSlice } from '@reduxjs/toolkit';
import { RootState } from '../../../store/store';

type ClassTeacherOpeningModal =
	| "ADD_TEACHER_TO_CLASS"
	| "ASSIGN_TEACHER_TO_SESSION"
	| "NONE";

type ClassTeacherSlice = {
	openingModal: ClassTeacherOpeningModal;
};

const initialState: ClassTeacherSlice = {
	openingModal: "NONE",
};


export const CLASS_TEACHER_SLICE_KEY = "classTeacherSlice";
export const classTeacherSlice = createSlice(
    {
        name: CLASS_TEACHER_SLICE_KEY,
        initialState,
        reducers: {
            closeModal: (state) => {
                state.openingModal = "NONE";
            },
            openTeacherAssignmenModal: (state) => {
                state.openingModal = "ADD_TEACHER_TO_CLASS";
            },
            openTeacherSessionAssigmentModal: (state) => {
                state.openingModal = "ASSIGN_TEACHER_TO_SESSION"
            }
        }
    }
)

export const classTeacherSelectors = {
    selectIsAssigningTeacher: (state: RootState) => state[CLASS_TEACHER_SLICE_KEY].openingModal === "ADD_TEACHER_TO_CLASS",
    selectIsAssigningTeacherToSession: (state: RootState) => state[CLASS_TEACHER_SLICE_KEY].openingModal === "ASSIGN_TEACHER_TO_SESSION",
}

export const classTeacherActions = classTeacherSlice.actions;

(and not until yesterday did I encounter a weird type inferring issues):

For some reason, typescript insist that the state parameter (red squiggles in the images above) implicitly has “any” type (and intellisense is off as well). I am 100% sure that all the state variable stored are either simple variables and object without function or Map or Set.

Additional type definition and store setup as in docs:

import {Action, configureStore, ThunkAction} from '@reduxjs/toolkit'
import rootReducer from "./rootReducer";
import {apiSlice} from "../features/CentralAPI";
import {rtkQueryErrorLogger} from "../middleware/ErrorToasterMiddleware";

export const store = configureStore({
    reducer: rootReducer,
    middleware: (getDefaultMiddleware) => {
        return getDefaultMiddleware().concat(apiSlice.middleware).concat(rtkQueryErrorLogger)
    }
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch

export type AppThunk<ReturnType = void> = ThunkAction<
    ReturnType,
    RootState,
    unknown,
    Action<string>
    >;

Expected Result:

state param type is inferred correctly (as ClassTeacherSlice in the code)

PS: typescript version: @4.4.2 | @reduxjs/toolkit: @1.7.0

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

16reactions
Medkhatcommented, May 13, 2022

Can you reproduce this issue in a CodeSandbox, or in a new project?

I tried to replicate the bug on code sandbox (reduced lots of codes and packages for security reasons), but things seem working fine on there: https://codesandbox.io/s/clever-marco-enfitg?file=/src/redux/features/Class/TeacherAPI/ClassTeacherSlice.tsx This must be some thing wrong with VS Code. Maybe the my project is too large and their was some kind of hard limit for TS compiler server (I did encounter heap overflow sometimes, compiling the project). Thus, I will close this issue and reopen it when i found something new Really appreciate your hard work and kind help, Mr. @markerikson

Hi there! I have the same issue, how did you fix it? ))

I didn’t manage to fix the problem though 😄 The problem seem to be some thing messed up with VS Code. Try using another IDE (In my case, I use WebStorm. The functionalities are good but the memory consumption is a bit high 😢 )

This was problem of Javascript and Typescript Nighly extension. Fixed)

image

5reactions
cremirdeviocommented, May 13, 2022

I had to disable Javascript and Typescript Nighly extension at least for now. And restart Vscode.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Typescript: generic type not correctly inferred (`unknown`)
inferred as unknown , so the reducer type is wrong, and the following will not cause a type error: const actions = slice({...
Read more >
TypeScript parsing incorrectly identifies function exports from ...
The displayed inferred type of the action creator is actually the signature of the associated reducer: (state, action: PayloadAction<CurrentRepo>) => void.
Read more >
Usage With TypeScript - Redux Toolkit
The easiest way of getting the State type is to define the root ... need to slightly modify the typing to correctly infer...
Read more >
Error A case reducer on a non-draftable value must not return ...
I'm trying to import typescript in my redux application. ... don't have to supply a type for state for each reducer, as it...
Read more >
Redux Toolkit Tutorial - 31 - TypeScript Support - YouTube
Courses - https://learn.codevolution.dev/ Support UPI - https://support.codevolution.dev/ Support Paypal ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found