绑定元素'Component'隐式具有'any'类型.ts

时间:2019-08-06 08:58:40

标签: reactjs typescript react-router-dom

新手在这里。我的以下代码有问题。我想定义一个受保护的“仪表板”页面,如下所示,但是却给了我这个绑定错误:

Binding element 'Component' implicitly has an 'any' type.ts(7031)


import * as React from "react";
import { Route, Router, Redirect } from "react-router-dom";
import Dashboard from "../features/dashboard";
import LoginContainer from "../features/login/containers/LoginContainer";
import SignUpContainer from "../features/signup/containers/SignUpContainer";
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default () => (
  <Router history={history}>
    <Route path="/" component={LoginContainer} />
    <Route path="/login" component={LoginContainer} />
    <Route path="/register" component={SignUpContainer} />

    <PrivateRoute path="/dashboard" component={Dashboard} />
  </Router>
);

function PrivateRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        localStorage.getItem("MyStoredUser") ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login"
            }}
          />
        )
      }
    />
  );
}

基本上,我使用的代码与此处相同:Protected routes and authentication with React Router v4eact Router - Redirects

我在做什么错了?

Error Img

1 个答案:

答案 0 :(得分:1)

您尚未定义任何类型,并且您显然已将打字稿配置为禁止在参数中隐式包含任何类型。您需要添加类型来满足打字稿编译器的要求:

import * as React from 'react';
import {Route, Router, Redirect, RouteProps} from 'react-router';

const PrivateRoute: React.FC<RouteProps> = ({ component: Component, ...rest }) => {
  return (
    // ... etc
  );
}