I am using Typescript 5.3.3 and I have reducer code that generates ts(2345) errors.
The reducer looks like this:
const initialState = Immutable.fromJS({
isLoading: false,
})
const myReducer = (state = initialState, action) => {
switch (action.type) {
case 'LOAD':
return state.set('isLoading', false) <--- ERROR
default: return state
}
}
This version generates an error on the marked line:
Argument of type 'boolean' is not assignable to parameter of type 'Map<"valueOf", Map<never, never>> | Map<"valueOf", Map<never, never>>'.ts(2345)
I have tried introducing an interface like this:
interface State {
isLoading: boolean
}
const initialState : State = Immutable.fromJS({ <--- ERROR 1
isLoading: false,
})
const myReducer = (state: State = initialState, action) : State => {
switch (action.type) {
case 'LOAD':
return state.set('isLoading', false) <--- ERROR 2
default: return state
}
}
But that generates two errors as marked above:
Property 'isLoading' is missing in type 'Map<"isLoading", Map<"valueOf", Map<never, never>>>' but required in type 'State'.ts(2741)Property 'set' does not exist on type 'State'.ts(2339)
The weird thing is that I have pretty much identical reducers (of the first type, i.e. with no interfaces) in other files where this works fine, so not sure why it doesn't work here.
Any ideas?
You are declaring
initialStateto be of typeState. However, the value you are assigning toinitialStateis the return value ofImmutable.fromJS(). This is the cause of your first error.Your second error is caused since TypeScript expects
stateto be of typeState. Since yourStatetype only consists of the single propertyisLoading,state.set()is not found.That being said, your initial code, works without error with TypeScript using [email protected] on Node 21.1 with TypeScript 5.2.2.