I'm trying to use react router with TypeScript. However, I have certain problems using withRouter function. On the last line, I'm getting pretty weird error:
Argument of type 'ComponentClass<{}>' is not assignable to parameter of type 'StatelessComponent<RouteComponentProps<any>> | ComponentClass<RouteComponentProps<any>>'.
Type 'ComponentClass<{}>' is not assignable to type 'ComponentClass<RouteComponentProps<any>>'.
Type '{}' is not assignable to type 'RouteComponentProps<any>'.
Property 'match' is missing in type '{}’
Code looks like:
import * as React from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps, withRouter } from 'react-router-dom';
interface HomeProps extends RouteComponentProps<any> {
}
interface HomeState { }
class Home extends React.Component<HomeProps, HomeState> {
constructor(props: HomeProps) {
super(props);
}
public render(): JSX.Element {
return (<span>Home</span>);
}
}
const connectModule = connect(
(state) => ({
// Map state to props
}),
{
// Map dispatch to props
})(Home);
export default withRouter(connectModule);
It looks like you have the right usage to apply the match, history, and location props to your component. I would check in your
node_modules
directory to see what versions ofreact-router
andreact-router-dom
you have, as well as the@types
modules.I have essentially the same code as you, and mine is working with the following versions:
This is a Typescript typings issue. Since withRouter() will provide the routing props you need at runtime, you want to tell consumers that they only need to specify the other props. In this case, you could just use a plain ComponentClass:
Or, if you had other props (defined in an interface called OwnProps) you wanted to pass in, you could do this:
There is slightly more discussion here
The way how I'm doing this:
I think it is a typescript typings compilation issue, but I've found a workaround:
After browsing the typescript definitions I discovered the
RouteComponentProps
interface so I now model my containers like sonow in the component class the route props can be accessed like this:
let teamid = this.props.match.params.teamId;
+1 for Ramon's answer. You can absolutely get full type coverage here. To add a bit - I added the call to withRouter.
my dependencies: