Eduardo Augusto
Eduardo Augusto

Reputation: 135

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?

Upvotes: 1

Views: 1924

Answers (1)

smac89
smac89

Reputation: 43234

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

Upvotes: 2

Related Questions