I'm trying to convert the way an alternate route component is defined in JSX an equivalent TypeScript TSX file. (1)
The JSX syntax is like this:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
localStorage.getItem('user')
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)} />
)
I've tried to convert it to TypeScript, but in Visual Studio, the <Component
part (see below) is underlined and the TypeScript compiler tells me
(TS) JSX element type 'Component' does not have any construct or call signatures.
I don't really understand the ({ component: Component, ...rest })
syntax of the lambda function. This is as far as I've gotten on writing it in TypeScript.
export function PrivateRoute(Component: React.Component, ...rest: any[]) {
return (
<Route {...rest} render={props => (
localStorage.getItem('user')
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)} />
);
};
Any suggestions?
References:
({ component: Component, ...rest })
means taking acomponent
attribute from the object via destructuring and renaming it toComponent
in the function scope, and putting the rest of the attributes of the object in a variable namedrest
through the "rest" operator (the...
). I hope that clears it up, I don't know TS so I can't help you refactor that :) – SrThompson