Home > database >  Finding difficulty in convert JS code to Typescript
Finding difficulty in convert JS code to Typescript

Time:12-13

I am converting my JavaScript code to Typescript. While I am working on routes page I am getting error as Binding element 'allowedRoles' implicitly has an 'any' type.

ProtectedRoutes.tsx

const ProtectedRoutes =  ({ allowedRoles }) => {
  const location = useLocation();
  const _user = { roles: [Role.USER] };

  return (
    _user?.roles?.find(item => allowedRoles?.includes(item))
      ? <RootPage />
      : _user
        ? <Navigate to="/denied" state={{ from: location }} replace />
        : <Navigate to="/signin" state={{ from: location }} replace />
  );
}

Routes.tsx

<Routes>
  <Route path="/" element={<RootPage />}>
    <Route
      element={
        <ProtectedRoutes
          allowedRoles={[
            Role.GLOBAL_ADMIN,
            Role.CUSTOMER_ADMIN
          ]}
        />
      }
    >
      <Route path="dashboard" element={<Dashboard />} />
    </Route>

    <Route
      element={
        <ProtectedRoutes
          allowedRoles={[
            Role.USER,
            Role.GLOBAL_ADMIN,
            Role.CUSTOMER_ADMIN
          ]}
        />
      }
    >
      <Route path="applications" element={<Applications />} />
    </Route>
  </Route>

  <Route path="/signin" element={<Signin />} />
  <Route path="/forgot-password" element={<ForgotPassword />} />
  <Route path="/denied" element={<PermissionDenied />} />
  <Route path='*' element={<NotFound />} />
</Routes>

CodePudding user response:

You need to assign a type to the props of the ProtectedRoutes component:

type ProtectedRoutesProps = {
  allowedRoles: Role[]
};

const ProtectedRoutes =  ({ allowedRoles }: ProtectedRoutesProps) => {
  const location = useLocation();
  const _user = { roles: [Role.USER] };

  return (
    _user?.roles?.find(item => allowedRoles?.includes(item))
      ? <RootPage />
      : _user
          ? <Navigate to="/denied" state={{ from: location }} replace />
          : <Navigate to="/signin" state={{ from: location }} replace />
  );
}
  • Related