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

前端 未结 3 660
悲&欢浪女
悲&欢浪女 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 {
      /* other props for ChildComponent */
    }
    const ChildComponent : React.SFC = ({ 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 = ({ history }) => (
      ..
    );
    

提交回复
热议问题