Correct type declaration for mapStateToProps Redux connection (TypeScript 2)

I have a Redux store and want to connect it. Here's an excerpt from my container component:

interface IProps  {
  states: IAppState;
  actions: IAppProps;
}
// mapping state to the props
const mapStateToProps = ( state: IAppState, ownProps = {} ) => ({
  states: state
});
// mapping actions to the props
const mapDispatchToProps = ( dispatch: Redux.Dispatch<IAppState> ) => ({
  actions: Redux.bindActionCreators( actions, dispatch )
});

// connect store to App
@connect<IAppState, IAppProps, any>(
  mapStateToProps,
  mapDispatchToProps
)
export default class App extends React.Component<IProps, {}> {
//...
}

      

When compiling, I get the following problem:

error TS2345: Argument of type '(state: IAppState, ownProps?: {}) => { states: IAppState; }' is not assignable to parameter of type 'MapStateToPropsParam<IAppState, any>'.
  Type '(state: IAppState, ownProps?: {}) => { states: IAppState; }' is not assignable to type 'MapStateToPropsFactory<IAppState, any>'.
    Type '{ states: IAppState; }' is not assignable to type 'MapStateToProps<IAppState, any>'.
      Type '{ states: IAppState; }' provides no match for the signature '(state: any, ownProps?: any): IAppState'.

      

I am using @ types / react-redux @ 4.4.44 which provides the MapStateToProps interface. I would think my mapStateToProps collides with this interface ... But something is wrong. Any ideas what this is?

+3


source to share


2 answers


Well, it seems to @types/react-redux

accept mapStateToProps

to return the exact same type that was accepted. I wanted it to change it for props during display, for example { states: AppStateTree }

. I changed the state tree instead combineReducers({ states: myReducer })

. So this code works great:



interface IRootState {
  state: IAppState;
}

const mapStateToProps = ( state: IRootState ) => state;

const mapDispatchToProps = {
  toggleOpenAddFeed
};

type IProps = IRootState & typeof mapDispatchToProps;

class App extends React.Component<IProps, {}> {
 render() {
    return (
      <div className="main-wrapper">
         <Mycomponent store={this.props} />
      </div>
    );
  }
}

export default connect( mapStateToProps, mapDispatchToProps )( App );

      

+1


source


ownProps

has no type. You must specify the type.



const mapStateToProps = ( state: IAppState, ownProps: any = {} )

      

0


source







All Articles