以打字稿友好的方式编写PrivateRoute组件

时间:2018-04-03 22:00:01

标签: typescript react-router-v4

我正在学习在Typescript中使用React Router。我也在阅读这篇关于如何在typescript + react路由器中实现PrivateRoutes的文章。

https://tylermcginnis.com/react-router-protected-routes-authentication/

上面的博客有一个代码段来实现PrivateRoute

const PrivateRoute = ({component: Component, ...rest}) => (
   <Route {...rest} render={(props) => (
      isLoggedIn.isAuthenticated === true ? <Component {...props} /> : <Redirect to='/login' />
   )} />
)

但是我的打字稿编译器不喜欢上面的代码

ERROR in [at-loader] ./src/components/Main.tsx:19:35
    TS7031: Binding element 'Component' implicitly has an 'any' type.
Child html-webpack-plugin for "index.html":

如何修改上面的代码,使其成为打字稿友好的?

2 个答案:

答案 0 :(得分:8)

renaming destructured properties有一个Typescript语法。

在建立专用路线时,看起来像这样:

%matplotlib inline

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np


fig = plt.figure(figsize=(10, 10))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines('10m')

y = np.linspace(40.0, 60.0, 30)
x = np.linspace(-10.0, 10.0, 40)
X, Y = np.meshgrid(x, y)
data = 2*np.cos(2*X**2/Y) - np.sin(Y**X)

cs = ax.contourf(X, Y, data, 3,
                 hatches=['//','+','x','o'],
                 alpha=0.5)
artists, labels = cs.legend_elements()

plt.legend(handles=artists, labels=labels)

plt.show()

答案 1 :(得分:2)

我使用以下代码模仿路线:

export const PrivateRoute = ({ component, ...rest }: RouteProps) => {
  if (!component) {
    throw Error("component is undefined");
  }

  const Component = component; // JSX Elements have to be uppercase.
  const render = (props: RouteComponentProps<any>): React.ReactNode => {
    if (fakeAuth.isAuthenticated) {
      return <Component {...props} />;
    }
    return <Redirect to={{ pathname: '/login' }} />
  };

  return (<Route {...rest} render={render} />);
}

Route的原始定义是Route<T extends RouteProps = RouteProps> extends React.Component<T, any>,但是对于Typescript 2.9,当前无法在第一行中将泛型运算符与泛型一起使用,这就是为什么使用常规RouteProps类型的原因。