Strongly typing the react-redux connect with typescript

后端 未结 2 1702
花落未央
花落未央 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:40

    Hope you don't mind if I remove some antipatterns from the code above. Please check the comments I've added. Also I've added withRouter to illustrate the pattern better

    import * as React from "react";
    import { bindActionCreators } from "redux";
    import { withRouter, RouteComponentProps } from "react-router";
    import { connect } from "react-redux";
    import { compose } from "recompose";
    
    // OUR ROOT REDUX STORE STATE TYPE
    import { State } from "../redux"; 
    
    import FileExplorer from "../components/file-explorer/file-explorer";
    
    // interfaces starting with 'I' is an antipattern and really
    // rarely needed to be in a separate file
    
    // OwnProps - that's what external code knows about out container
    type OwnProps = {};
    
    // this comes from redux
    type StateProps = {
      fileExplorer: FileDirectoryTree | null;
    };
    
    // resulting props - that what container expects to have
    type Props = OwnProps & StateProps & RouteComponentProps;
    
    // no need to have a class, SFC will do the same job
    const SideMenu: React.SFC = props => {
      return (
        
    {this.props.fileExplorerInfo !== null && ( )}
    ); }; // compose (from recompose lib) because usually we have more than 1 hoc // say let's add withRouter just for fun export default compose( withRouter, // it's important to read the typings: // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts connect(s => ({ fileExplorerInfo: s.fileExplorer })), )(SideMenu);

提交回复
热议问题