Typescript: How to add type check for history object in React?

前端 未结 3 611
悲&欢浪女
悲&欢浪女 2021-02-01 12:22

I have the following piece of code, which receives a history object as prop:

const ChildComponent = ({ history }) => (
        
相关标签:
3条回答
  • 2021-02-01 13:01

    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 }) => (
      ..
    );
    
    0 讨论(0)
  • 2021-02-01 13:06

    For React 16.8 with hooks:

    ...
    import {withRouter, RouteComponentProps} from 'react-router-dom';
    ...
    const ChildComponent: React.FunctionComponent<RouteComponentProps> = ({history}) => {
    ...
    }
    
    0 讨论(0)
  • 2021-02-01 13:16

    The simplest solution I found

    import { RouteComponentProps } from 'react-router-dom';
    
    ....
    
    interface Foo {
       location: RouteComponentProps.location;
       history: RouteComponentProps.history;
       match: RouteComponentProps.match;
    }
    
    0 讨论(0)
提交回复
热议问题