Strongly typing the react-redux connect with typescript

后端 未结 2 1700
花落未央
花落未央 2021-02-02 15:31

I am getting an error trying to type the parameters for my react component. I would like to stronly type what properties will be on the props and state of a component, but when

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 15:59

    When using generics, you are getting the place of interfaces wrong:

    When you declare your React component:

    class Comp extends Component
    

    With ICompProps and ICompState are your component's props and internal state respectively.

    When you use connect:

    connect
    

    IMapStateToProps represents what is returned by your mapStateToProps() function. IMapDispatchToProps represents what is returned by your mapDispatchToProps() function. ICompProps represents your React component props (same as above) IReduxState represents your App's Redux State

    So in your particular example:

    When declaring your React component:

    class SideMenu extends Component
    

    Use ISideMenu for the props and {} (empty state) for the state as you don't use any state.

    When using connect:

    connect(mapStateToProps)(SideMenu);
    

    You can use ISideMenu as both your React component props and the object returned by mapStateToProps. But in practice it might be best to create 2 separate interfaces.

    In my apps, I usually can't be bothered typing the mapStateToProps return object so I simply use:

    connect<{}, {}, ISideMenu, ISideMenuState>(mapStateToProps)(SideMenu);
    

提交回复
热议问题