TypeScript Removing Repetitive Property Assignment with React-Redux

Viewed 118

I am using TS React Redux and my app state looks something like this

type AppState = {
   foo: number
   bar: number
   baz: number
}

and I have a component whose hooked up to redux like so

type ComponentState = {
   foo: number
   bar: number
}

function mapStateToProps(state: AppState): ComponentState{
   return {
      foo: state.foo,
      bar: state.bar
   }
}

My question is that in mapStateToProps, is there any way to copy over the props without having to select each one individually? Since ComponentState is a subset of AppState I feel like there is an obvious way to do this that I'm missing.

2 Answers

If you're using connect and TypeScript together, we specifically recommend using the ConnectedProps<T> pattern to infer the type of all the props passed from connect to your component. That will eliminate the need to write that ComponentState interface if you don't want to, as TS will also infer the return type of mapState.

You should also consider using our useSelector hook in function components, as it's easier to type than connect is.

you can destructure the items you want to use, however a mapStateToProps function is the place where you define what to take out of the state to give to the component.

function mapStateToProps({foo, bar}: AppState): ComponentState {
   return { foo, bar }
}

if you were wanting to do a more functional approach you could do something like this

const myComponentKeys: Array<keyof ComponentState> = ['foo', 'bar']
function mapStateToProps(state: AppState): ComponentState {
   return pick(myComponentKeys, state)
}
Related