'Property 'user' does not exist on type 'WritableDraft<{ name: string; }>'

i'm new with TypeScript. I'm trying to use TypeScript with Redux but i'm blocked with this error: Property 'user' does not exist on type 'WritableDraft<{ name: string; }>'. I was going step by step with tutorial on Youtube but it's not working on my project. Any ideas?

Here's my code:

import { createSlice } from '@reduxjs/toolkit';
import React from 'react';

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    name: '',
  },
  reducers: {
    login: (state, action) => {
      state = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state: { user: { user: any } }) => state.user.user;

export default userSlice.reducer;


Solution 1:[1]

The data shape of the user state slice is { name: string }.

import { combineReducers, configureStore, createSlice } from '@reduxjs/toolkit';

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    name: '',
  },
  reducers: {
    login: (state, action) => {
      state.name = action.payload;
    },
    logout: (state) => {
      state.name = '';
    },
  },
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state: { user: { name: string } }) => state.user;

const store = configureStore({ reducer: combineReducers({ user: userSlice.reducer }) });
console.log(store.getState());
store.subscribe(() => {
  console.log('selectUser:', selectUser(store.getState()));
});

console.log(store.dispatch(login('John')));

Logs:

{ user: { name: '' } }
selectUser: { name: 'John' }
{ type: 'user/login', payload: 'John' }

Solution 2:[2]

If you've cross checked your code and its fine.

Change the version of redux-toolkit to a previous one, in my case, I used 1.8.0 and everything started working again.

Or delete node_modules and run npm install or yarn

Solution 3:[3]

As the user devordem commented python -c "print('A'*(4*16) + \"\x0a\x0d\x0a\x0d\")" The following code did work i had tried wrapping everything myself but forgot the \ before "\xoa

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 slideshowp2
Solution 2
Solution 3 Harsh Verma