How to type Redux state in TypeScript to create new state without item

只愿长相守 提交于 2019-12-13 07:43:40

问题


I'm using TypeScript 2.x and Redux. I have a reducer which receives an action, based on which I wish to create a new state without some item like this:

export function reducer(state = {}, action) {
  switch (action.type) {
    case SOME_ACTION:      
      let newState : { something: string } = state;
      delete newState.something;
      return newState;
    default:
      return state;
  }
}

Thanks to @basarat I figured out the basics of deleting things ( see TypeScript 2: Remove item from 2-field object). The code above is based on that advice, but now I instead get

    TS2322: Type '{}' is not assignable to type '{ something: string; }'.
  Property 'something' is missing in type '{}'. 

As far as I understand this means that I need to somehow infer the type of the incoming state to delete this item.

What's the best approach to type the Redux state? Or is there an alternative to my approach?


回答1:


Don't do mutating state with redux. E.g. the following is not a good idea

delete newState.something;

Instead create a new object without that prop e.g.

const {something, ...newState} = state;
return newState;

Beyond that you need to annotate state. For a quick hack you can simply any:

export function reducer(state:any = {}, action) {

But you should read on doing a better annotation if you are still confused : https://basarat.gitbooks.io/typescript/docs/types/type-system.html



来源:https://stackoverflow.com/questions/45230325/how-to-type-redux-state-in-typescript-to-create-new-state-without-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!