Type 'MyType' is not assignable to type 'WritableDraft<MyType>'
Asked Answered
R

4

11

I use @reduxjs/toolkit and my state contains: allSlides: ISlide[];

When I try to change anything in allSlides like ex.

setAllSlides(state, action: PayloadAction<ISlide[]>) {
  state.allSlides = action.payload;
},
storeNewSlide(state, action: PayloadAction<ISlide>) {
  state.allSlides.push(action.payload);
},

I get a TS error

Type 'ISlide' is not assignable to type 'WritableDraft<ISlide>'

I don't have problem with changing array of primitive values or just one property in objects, but I don't know how to change correctly whole array or specific object in array.

Ripplet answered 25/4, 2022 at 12:46 Comment(0)
C
3

Had similar issue, I think redux doesn't like direct mutation of state object.

so spread operator solved for me

setAllSlides(state, action: PayloadAction<ISlide[]>) {
  state = { ...state, allSlices:action.payload };
},
storeNewSlide(state, action: PayloadAction<ISlide>) {
  state = { ...state, allSlices: [...state.allSlices, action.payload } ];
},
Cheboksary answered 4/12, 2022 at 15:33 Comment(2)
This is likely true of redux, but not when using Redux Toolkit as it uses Immer internally. See redux-toolkit.js.org/usage/immer-reducersDurbin
Following @Kristopher's lead, I see this works for me: Object.assign(state, { allSlices: action.payload });Toolmaker
P
2

You have to add the type in the action

ie:

export const storeNewSlide = createAsyncThunk(
  "slides/storeNewSlide",
  async (slide: ISlide) => {
    return {
      slide,
    };
  }
);

and then in your allSlides:

storeNewSlide(state, action: PayloadAction<ISlide>) {
  state.allSlides.push(action.payload.slide);
},

Same for the array of slides

Pierce answered 6/6, 2022 at 18:54 Comment(1)
Interestingly this fixed it. So it's a mere argument type issue, no runtime code should be changed.Feaze
I
0

Try providing the type of 'state' in the reducer. It worked for me.

Idolatry answered 28/12, 2023 at 12:41 Comment(0)
S
-1

I've had similar issue. Resolved by import type on type. in my case :

import { Comment } from "./commentType"; //import Comment

export interface Movie {
  id: number;
  title: string;
  release_date: Date;
  genre: string;
  director: string;
  description: string;
  thumbnail: string;
}

export interface MovieResponse extends Movie {
  rating: number;
  comments: Comment[]; //this Comment type not imported before
  isWatchlist: boolean;
}
Strep answered 2/2 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.