简体   繁体   中英

Typescript error in ReactJS - Property does not exist on type

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM