React Router TypeScript errors withRouter

Viewed 301

I have two functions, A and Tour.

Function A calls Tour function.

interface TourProp {
  isOpen : boolean,
  closeTour : () => void,
}

const A: React.FC<TourProp> = () => {
  const [isTourOpen, SetTourOpen] = useState(false);

  const closeTour = () => {
    SetTourOpen(false);
  };

  const openTour = () => {
    SetTourOpen(true);
  };

  return (
    <div>
      ...
      <Tour isOpen={isTourOpen} closeTour={closeTour} />
    </div>
  );
};

But in the Tour function, if I do this,

const Tour : React.FC<TourProp> = withRouter(
  ({isOpen, closeTour, location: { pathname }, history }) => {
    const steps = [
      {
        selector: ".nav",
        content: "This is the Navigation"
      },
      ...(pathname === "/"
        ? [
            {
              selector: ".home",
              content: "This is the Home Content",
              action: () => history.push("/topics")
            }
          ]
         : [
            {
              selector: ".topic1",
              content: "Rendering with React"
            },
            {
              selector: ".topic2",
              content: "Components"
            },
            {
              selector: ".topic3",
              content: "Props v. State"
            }
          ])
       ];
      ....
}

I get the following errors,

Property 'isOpen' does not exist on type 'RouteComponentProps<any, StaticContext, unknown> & { children?: ReactNode; }'.

Property 'closeTour' does not exist on type 'RouteComponentProps<any, StaticContext, unknown> & { children?: ReactNode; }'.

Type 'ComponentClass<Pick<RouteComponentProps<any, StaticContext, unknown>, never>, any> & WithRouterStatics<({ isOpen, closeTour, location: { pathname }, history }: PropsWithChildren<RouteComponentProps<any, StaticContext, unknown>>) => Element>' is not assignable to type 'FC'.

Type 'ComponentClass<Pick<RouteComponentProps<any, StaticContext, unknown>, never>, any> & WithRouterStatics<({ isOpen, closeTour, location: { pathname }, history }: PropsWithChildren<RouteComponentProps<any, StaticContext, unknown>>) => Element>' provides no match for the signature '(props: PropsWithChildren, context?: any): ReactElement<any, string | JSXElementConstructor> | null'.

I am new to TypeScript, any leads on what I am missing?

1 Answers

you just need to add your type declaration to the withRoute function:

const Tour : React.FC<TourProp> = withRouter<TourProp>(

but note your type must contain the normal withRoute properties like history, location, and the rest if not you would end up have those ones missing to solve that import RouteComponentProps from react-router then use as follows

const Tour : React.FC<TourProp> = withRouter<RouteComponentProps<TourProp>>(
Related