1

I'm trying to make an authentication app using react-router-dom and a typescript problem is annoying me for days. I have my index.tsx that uses a custom component "PrivateRoute" that only allows the user to access some route if he/she is authenticated.

ReactDOM.render(
  <BrowserRouter>
    <QueryClientProvider client={queryClient}>
      <Switch>
        <Route path="/login" exact component={Login} />
        <PrivateRoute path="/" exact component={() => <h1>Home</h1>} />
        <PrivateRoute path="/teste" exact component={() => <h1>Testando</h1>} />
      </Switch>
    </QueryClientProvider>
  </BrowserRouter>,
  document.getElementById("root")
);

Below is the PrivateRoute component:

interface IPrivateRouteProps {
  component: React.ElementType;
}

export function PrivateRoute({
  component: Component,
  ...rest
}: IPrivateRouteProps): JSX.Element {
  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated() ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{ pathname: "/login", state: { from: props.location } }}
          />
        )
      }
    />
  );
}

Typescript is giving the following error:

Type '{ path: string; exact: true; component: () => Element; }' is not assignable to type 'IntrinsicAttributes & IPrivateRouteProps'.
  Property 'path' does not exist on type 'IntrinsicAttributes & IPrivateRouteProps'.

I don't know what i am doing wrong, since i am using the spread operator to get all of the "extra" properties from the component aside from the "component" property from the "IPrivateRouteProps" interface . Can someone help me?

1 Answer 1

2

You need to tell typescript that your IPrivateRouteProps also includes props from Route:

interface IPrivateRouteProps extends RouteProps {
  component: React.ElementType;
}

Provided you are using @types/react-router, RouteProps is defined here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. I updated my interface so it now looks like the following: interface IPrivateRouteProps extends RouteProps { component: React.ComponentType<RouteComponentProps>; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.