user1354934 user1354934 - 3 months ago 9
TypeScript Question

TypeScript error number is not assignable

I am writing a reducer and I want RESET to do

state.count = 0
. However, this gives me an error that
number is not assignable to type CounterState
.

Here is my code:

export interface CounterState {
count: number;
};

const initialState: CounterState = {
count: 0
};

export default function counter(state = initialState, action: Action): CounterState {
switch (action.type) {
case TYPES.INCREMENT:
return assign({}, state, {
count: state.count + 1
});
case TYPES.DECREMENT:
return assign({}, state, {
count : state.count - 1
});
case TYPES.RESET:
//error here
return state.count=0;
default:
return state;
}
}


I am using lodash's assign function. Thanks

Answer

You have specified the return type of your function as CounterState, but for the reset case, you are trying to return a number (state.count=0 evaluates to the number on the right, so you are returning 0)

Instead you should return a state object either using the initialState constant

case Types.RESET:
    return initialState;

Or using the assign as well here, if you have other properties on the state, you wish to preserve

case Types.RESET:
    return assign({}, state, {
      count : 0
    });