Max Travis
Max Travis

Reputation: 1318

TypeScript/Redux. Cannot write interface for Reducer. Error TS2322

I cannot understand, why I always gets an error once use the interface ITitleIconSwitch with declarated type for state in it.

interface ITitleIconSwitch {
  'TITLE_ICON_SWITCH': (state: object) => {
    state: object; // this line provides me with an error stack. But! Without 'state' interface works fine. Why?
    titleSwitch: boolean;
  }
}

const actionHandlers: ITitleIconSwitch = {
  'TITLE_ICON_SWITCH': state => ({
    ...state,
    titleSwitch: false
  })
}

The error message:

TS2322:

Type '{ [TITLE_ICON_SWITCH]: (state: object) => { titleSwitch: false; }; }' is not assignable to type 'IActionHandlers'.

Type '{ [TITLE_ICON_SWITCH]: (state: object) => { titleSwitch: false; }; }' is not assignable to type 'IStateUpdate'.

Property ''STATE_UPDATE'' is missing in type '{ [TITLE_ICON_SWITCH]: (state: object) => { titleSwitch: false; }; }'.

Upvotes: 0

Views: 196

Answers (1)

Sviat Kuzhelev
Sviat Kuzhelev

Reputation: 1788

You need to write your types for reducer as function, not like object, because you declare you reducer in like object-oriented style. So you need to do the same with types for this reducer:

export interface ITitleIconSwitch { . // typing for reducer
  [TITLE_ICON_SWITCH]: (state: object) => {
    titleSwitch: boolean
  }
}

export interface ITitleState { // typing for reducer state
  titleSwitch: boolean
}

and then add them to the particular reducer:

const actionHandlers: IActionHandlers = {
  [TITLE_ICON_SWITCH]: (state: ITitleState) => ({
    ...state,
    titleSwitch: false
  })
}

Upvotes: 1

Related Questions