【问题标题】:Typescript error in ReactJS - Property does not exist on typeReactJS 中的打字稿错误 - 类型上不存在属性
【发布时间】:2021-10-23 11:34:28
【问题描述】:

我正在尝试使用 react-router-dom 制作一个身份验证应用程序,并且打字稿问题困扰了我好几天。我的 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")
);

下面是 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 出现以下错误:

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

我不知道我做错了什么,因为我使用扩展运算符从“IPrivateRouteProps”接口中获取“组件”属性之外的所有“额外”属性。有人可以帮我吗?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    你需要告诉 typescript 你的IPrivateRouteProps 还包含来自Route 的道具:

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

    如果你使用@types/react-router,RouteProps 定义为here

    【讨论】:

    • 感谢您的帮助。我更新了界面,现在看起来如下所示:interface IPrivateRouteProps extends RouteProps { component: React.ComponentType&lt;RouteComponentProps&gt;; }
    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2018-10-19
    • 2018-11-30
    • 2020-05-05
    • 2017-03-02
    • 2021-09-07
    相关资源
    最近更新 更多