0

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?

langkilde
  • 1,473
  • 1
  • 20
  • 37

1 Answers1

0

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

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Thanks for the quick feedback @basarat. I understand I should not mutate the state, which is why I've tried to a create a new state. The suggestion you made results in a similar error as before ```TS2459: Type '{}' has no property 'something' and no string index signature. ``` which leads me to think I still need to type the state somehow. – langkilde Jul 21 '17 at 06:22
  • Yeah you need to annotate it – basarat Jul 21 '17 at 07:46