Typescript: How to add type check for history object in React?
You can use the RouteComponentProps
interface, which declares all props passed by withRouter
:
import { RouteComponentProps } from 'react-router-dom';
..
interface ChildComponentProps extends RouteComponentProps<any> {
/* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
..
);
The type parameter to RouteComponentProps
is the type of the params
property in match
, so you won't need it unless you're matching named path segments.
Alternatively, if history
doesn't come from withRouter
but is passed by itself as a prop, you can import the type from history
:
import { History } from 'history';
..
interface ChildComponentProps {
history : History
/* other props for ChildComponent */
}
const ChildComponent : React.SFC<ChildComponentProps> = ({ history }) => (
..
);
The simplest solution I found
import { RouteComponentProps } from 'react-router-dom';
....
interface Foo{
history: RouteComponentProps["history"];
location: RouteComponentProps['location'];
match: RouteComponentProps['match'];
}
For React 16.8 with hooks:
...
import {withRouter, RouteComponentProps} from 'react-router-dom';
...
const ChildComponent: React.FunctionComponent<RouteComponentProps> = ({history}) => {
...
}