I am working on a React with typescript app and would like to prevent some pages to be accessed for non authenticated users.
So far I have this:
import { Redirect, Route, RouteProps } from 'react-router'
export interface ProtectedRouteProps extends RouteProps {
isAuthenticated: boolean
isAllowed: boolean
restrictedPath: string
authenticationPath: string
}
export const ProtectedRoute = (props: ProtectedRouteProps) => {
let redirectPath = ''
if (!props.isAuthenticated) {
redirectPath = props.authenticationPath
}
if (props.isAuthenticated && !props.isAllowed) {
redirectPath = props.restrictedPath
}
if (redirectPath) {
const renderComponent = () => <Redirect to={{ pathname: redirectPath }} />
return <Route {...props} component={renderComponent} render={undefined} />
} else {
return <Route {...props} />
}
}
export default ProtectedRoute
For some reason Typescript throws some compile errors at these lines:
if (redirectPath) {
const renderComponent = () => <Redirect to={{ pathname: redirectPath }} />
return <Route {...props} component={renderComponent} render={undefined} />
} else {
return <Route {...props} />
}
Redirect shows: (alias) class Redirect import Redirect Parsing error: '>' expected.
redirectPath shows: const redirectPath: any Binding element 'redirectPath' implicitly has an 'any' type
Route in else stm shows: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)
update: my package.json does not have react-router but has react-router-dom might this be problem?