I
I
Incold2020-10-10 21:49:23
typescript
Incold, 2020-10-10 21:49:23

Why am I getting error TS2322?

Hello! Let me show you the code first:

<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>

Interfaces
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;


Error:
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'.

Why does an error appear with access, because IPrivateRoute is inherited from IRoute, and, in theory, access should not affect IRoute in any way, and what can the first error be connected with?
Thanks in advance,

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-10-11
@bingo347

routes.map((route: IPrivateRoute | IRoute) => route.access // Здесь ошибка, так как в IRoute нет поля access, а значит нет и в юнионе IPrivateRoute | IRoute
  ? <PrivateRoute key={route.path} {...route}/> // а здесь, так как route.access не является тайп-гвардом, и не смотря на условие, тип по прежнему IPrivateRoute | IRoute

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question