简体   繁体   English

ReactJS 中的 Typescript 错误 - 类型上不存在属性

[英]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.我正在尝试使用 react-router-dom 制作一个身份验证应用程序,一个 typescript 问题让我烦恼了好几天。 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.我的 index.tsx 使用自定义组件“PrivateRoute”,该组件仅允许用户在经过身份验证后访问某些路由。

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:下面是 PrivateRoute 组件:

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: Typescript 给出以下错误:

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.我不知道我做错了什么,因为我使用扩展运算符从“IPrivateRouteProps”接口的“组件”属性之外获取组件的所有“额外”属性。 Can someone help me?有人能帮我吗?

You need to tell typescript that your IPrivateRouteProps also includes props from Route :您需要告诉 typescript 您的IPrivateRouteProps还包括来自Route的道具:

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

Provided you are using @types/react-router , RouteProps is defined here如果您使用的是@types/react-routerRouteProps在此处定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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