正确的Redux connect的mapStateToProps类型声明(TypeScript 2)

Dmi*_*iko 5 reactjs react-redux typescript2.0

我有一个Redux商店,想要连接它。这是我的容器组件的摘录:

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, {}> {
//...
}
Run Code Online (Sandbox Code Playgroud)

编译时收到以下问题:

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'.
Run Code Online (Sandbox Code Playgroud)

我正在使用@ types / react-redux @ 4.4.44,它公开了MapStateToProps接口。我会认为我的mapStateToProps遇到了这个接口……但是出了点问题。有什么想法吗?

Dmi*_*iko 7

好吧,似乎@types/react-redux接受mapStateToProps返回与接收的类型完全相同的类型。我希望它在映射期间修改它的 props,例如{ states: AppStateTree }. 相反,我修改了状态树combineReducers({ states: myReducer })。所以这段代码工作正常:

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 );
Run Code Online (Sandbox Code Playgroud)