My state data:
options: [
{
id: 1,
name: "Sale",
isTrue: false,
},
{
id: 2,
name: "New in",
isTrue: false,
},
],
And, in reducers I have:
closeOptions: (state) => {
state.options = state.options.map((item) => (item.isTrue = false));
},
But I am getting error in state.options with red underline in vscode. And, it shows below error:
Type 'boolean[]' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>[]'.
Type 'boolean' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>'.ts(2322)
More,
Unhandled Runtime Error
TypeError: Cannot create property 'isTrue' on boolean 'false'
Source
105 | closeOptions: (state) => {
> 106 | state.options = state.options.map((item) => (item.isTrue = false));
| ^
107 | },
How can I resolve this issue?
Whole project in TS
>Solution :
You’re getting these errors:
Type 'boolean[]' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>[]'.
Type 'boolean' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>'.ts(2322)
Because when you use state.options.map((item) => (item.isTrue = false)) in closeOptions it’s returning [false, false] whose type is boolean[] which is completely different from type WritableDraft<{ id: number; name: string; isTrue: boolean; }>[].
Change closeOptions function to this:
closeOptions: (state) => {
state.options?.forEach((item) => (item.isTrue = false))
}