Why do I get a TS message "Property 'value' may not exist on type 'boolean'. Did you mean 'valueOf'?" when setting state with RTK in React?

Why do I get a TS message "Property 'value' may not exist on type 'boolean'. Did you mean 'valueOf'?" when setting state with RTK in React?

Problem Description:

In creating a slice with Redux Toolkit in the Visual Studio Code code editor I am getting a TS warning "Property ‘value’ may not exist on type ‘boolean’. Did you mean ‘valueOf’?" when setting state value to boolean as such:

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

export const authSlice = createSlice({
    name: 'auth',
    initialState: false, // not logged-in
    reducers: { // functions to update state
        login: (state) => {state.value = true},
        logout: (state) => {state.value = false}
    }
});

Also, I am using JavaScript, not TypeScript, which makes it make even less sense.
What am I misunderstanding and/or doing wrong?

Solution – 1

I believe that your initial state should be an object rather than a boolean for it to work. Try instead:

initialState: {
  value: false,
}

Solution – 2

I solved it by leveraging FedToaster’s suggestion and correcting the code as such:

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

export const authSlice = createSlice({
    name: 'auth',
    initialState: {value: false}, // not logged-in
    reducers: { // functions to update state
        login: state => {state.value = true},
        logout: state => {state.value = false}
    }
});
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject