How to use TypeScript with withRouter, connect, React.Component and custom properties?

chmielot picture chmielot · Feb 27, 2018 · Viewed 12.4k times · Source

I have a React Component that uses connect, withRouter and receives custom properties. I am trying to convert this to TypeScript and I'm wondering if I'm doing this correctly. At least, I have no errors, now.

This is the code that shows the concept:

import * as React from 'react'
import { connect } from 'react-redux';
import { withRouter, RouteComponentProps } from 'react-router';

import { 
  fetchTestLists,
  newTestList,
  displayTestList,
} from '../../../actions/index';

interface StateProps {
  testList: any;    // todo: use the type of state.myList to have validation on it
}

interface DispatchProps {
  fetchTestLists: () => void;
  newTestList: () => void;
  displayTestList: (any) => void;   // todo: replace any with the actual type
}

interface Props {      // custom properties passed to component
  className: string;
}

type PropsType = StateProps & DispatchProps & Props;


class MyTest extends React.Component<PropsType & RouteComponentProps<{}>, {}> {
  constructor(props) {
    super(props);
    this.handleCellClick = this.handleCellClick.bind(this);
    this.newTestList = this.newTestList.bind(this);
  }

  componentDidMount() {
    this.props.fetchTestLists();
  }

  handleCellClick(row, column, event) {
    this.props.displayTestList(row);
  }

  newTestList(e) {
    this.props.newTestList()
  }

  render() {
    return (
      <div className={this.props.className}>
      </div>
    );
  }
}

const mapStateToProps = (state): StateProps => ({
  testList: state.myList,   // todo: define a type for the root state to have validation here
});

const dispatchToProps = {
  fetchTestLists,
  newTestList,
  displayTestList,
};

export default withRouter<Props & RouteComponentProps<{}>>(connect<StateProps, DispatchProps>(
  mapStateToProps,
  dispatchToProps,
)(MyTest) as any);

The component is used like this: <MyTest className={"active"} />

I had to experiment a lot to get this working. For example:

1) When I leave out the types for withRouter like this: export default withRouter(connect... Then I get TS2339: Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<RouteComponentProps<any>, never>, C...'. This has somehow been suggested here: React router in TypeScript- both router and own props, although I have no understanding of that concept.

2) If you are wondering about the last line as any, this is related to https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18999 and I'm getting this error without it:

 TS2345: Argument of type 'ComponentClass<Pick<any, never>> & { WrappedComponent: ComponentType<any>; }' is not assignable to parameter of type 'ComponentType<Props & RouteComponentProps<{}>>'.
 Type 'ComponentClass<Pick<any, never>> & { WrappedComponent: ComponentType<any>; }' is not assignable to type 'StatelessComponent<Props & RouteComponentProps<{}>>'.
 Type 'ComponentClass<Pick<any, never>> & { WrappedComponent: ComponentType<any>; }' provides no match for the signature '(props: Props & RouteComponentProps<{}> & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.

So is this the right way to do it? Where do you see issues? I am basically using all the latest versions, here is a snippet from my package.json:

"react": "^16.2.0",
"redux": "^3.7.2",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "^4.0.8",
...
"typescript": "^2.7.2",
"@types/react-redux": "^5.0.15",
"@types/react-router": "^4.0.22",
"@types/react-router-dom": "^4.2.4",
"@types/react": "^16.0.38",
"@types/react-dom": "^16.0.4",

Answer

Kaca992 picture Kaca992 · Jan 25, 2020

How I do it in our projects (this is the easiest way and you can get intellisense when you use it):

import * as React from 'react'
import { connect } from 'react-redux';
import { withRouter, RouteComponentProps } from 'react-router';

import { 
  fetchTestLists,
  newTestList,
  displayTestList,
} from '../../../actions/index';

interface StateProps {
  testList: any;    // todo: use the type of state.myList to have validation on it
}

interface DispatchProps {
  fetchTestLists: () => void;
  newTestList: () => void;
  displayTestList: (any) => void;   // todo: replace any with the actual type
}

interface Props extends RouteComponentProps {      // custom properties passed to component
  className: string;
}

type PropsType = StateProps & DispatchProps & Props;


class MyTest extends React.Component<PropsType> {
  constructor(props) {
    super(props);
    this.handleCellClick = this.handleCellClick.bind(this);
    this.newTestList = this.newTestList.bind(this);
  }

  componentDidMount() {
    this.props.fetchTestLists();
  }

  handleCellClick(row, column, event) {
    this.props.displayTestList(row);
  }

  newTestList(e) {
    this.props.newTestList()
  }

  render() {
    return (
      <div className={this.props.className}>
      </div>
    );
  }
}

const mapStateToProps = (state, ownProps: Props): StateProps => ({
  testList: state.myList,   // todo: define a type for the root state to have validation here
});

const dispatchToProps: DispatchProps = {
  fetchTestLists,
  newTestList,
  displayTestList,
};

export default withRouter(connect(
  mapStateToProps,
  dispatchToProps,
)(MyTest));

Also if this is something you will type often I recommend writing a custom snippet (if you are using something like VS Code it is very easy).