@Incold

Почему я получаю ошибку TS2322?

Здравствуйте! Сначала покажу код:
<Switch>
            {
                routes.map((route: IPrivateRoute | IRoute) => route.access // Здесь
                    ? <PrivateRoute key={route.path} {...route}/> // и здесь появляется ошибка
                    : <Route key={route.path} to={route.path} render={
                        () => route.redirect ? <Redirect to={route.redirect} /> : route.component
                    } />)
            }
</Switch>

Интерфейсы
export interface IRoute {
    path: string
    component?: typeof React.Component | React.FC
    exact?: boolean
    subRoutes?: Array<IRoute | IPrivateRoute>
    redirect?: string
}

export interface IPrivateRoute extends IRoute {
    component: typeof React.Component | React.FC
    access: boolean
    redirect: string
}

PrivateRoute.tsx
const PrivateRoute = ({component: Component, access, redirect, ...rest}: IPrivateRoute) => {
    return (
        <Route {...rest} render={props => access
            ? <Component {...props}/>
            : <Redirect to={redirect}/>}
        />
    )
}

export default PrivateRoute;


Ошибка:
TS2322: Type '{ path: string; component?: typeof Component | FC<{}> | undefined; exact?: boolean | undefined; subRoutes?: (IRoute | IPrivateRoute)[] | undefined; redirect?: string | undefined; key: string; } | { ...; }' is not assignable to type 'IntrinsicAttributes & IPrivateRoute'.   Property 'access' is missing in type '{ path: string; component?: typeof Component | FC<{}> | undefined; exact?: boolean | undefined; subRoutes?: (IRoute | IPrivateRoute)[] | undefined; redirect?: string | undefined; key: string; }' but required in type 'IPrivateRoute'.

Почему появляется ошибка с access, ведь IPrivateRoute наследуется от IRoute, и по идее access никак не должен влиять на IRoute и с чем может быть связана первая ошибка?
Заранее, спасибо, за любую помощь?
  • Вопрос задан
  • 6425 просмотров
Пригласить эксперта
Ответы на вопрос 1
bingo347
@bingo347 Куратор тега TypeScript
Crazy on performance...
routes.map((route: IPrivateRoute | IRoute) => route.access // Здесь ошибка, так как в IRoute нет поля access, а значит нет и в юнионе IPrivateRoute | IRoute
  ? <PrivateRoute key={route.path} {...route}/> // а здесь, так как route.access не является тайп-гвардом, и не смотря на условие, тип по прежнему IPrivateRoute | IRoute
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы