Home > Software engineering >  Why do I get a TS message "Property 'value' may not exist on type 'boolean'
Why do I get a TS message "Property 'value' may not exist on type 'boolean'

Time:12-07

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?

CodePudding user response:

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

initialState: {
  value: false,
}

CodePudding user response:

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}
    }
});
  • Related