user1354934 user1354934 - 1 year ago 104
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) {
return assign({}, state, {
count: state.count + 1
return assign({}, state, {
count : state.count - 1
//error here
return state.count=0;
return state;

I am using lodash's assign function. Thanks

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download