Liam_1998
Liam_1998

Reputation: 1477

Typescript with dynamic map router got type error

Using Typescript and react-router-dom. I declare an array to dynamic generate the Route child in Switch. But got the type error:

Conversion of type '{ routeMap: RouteProps<string, { [x: string]: string | undefined; }>[]; "": any; }' to type 'Switch' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type '{ routeMap: RouteProps<string, { [x: string]: string | undefined; }>[]; "": any; }' is missing the following properties from type 'Switch': context, setState, forceUpdate, render, and 3 more.

Here is my code:

import { RouteProps, Switch, Redirect, Route } from 'react-router-dom'

export const routeMap: RouteProps[] = [
  {
    path: '/',
    exact: true,
    component: loadable(() => import('Views/Home')),
  },
  {
    path: `${base}`,
    exact: true,
    component: loadable(() => import('Views/Home')),
  },
  {
    path: `${base}/index`,
    component: loadable(() => import('Views/Home')),
  },
  {
    path: `${base}/404`,
    component: loadable(() => import('Views/404')),
  },
  {
    path: `${base}/floorConstruct`,
    component: loadable(() => import('Views/FloorConstruct')),
  },
  {
    path: `${base}/dataTracking`,
    component: loadable(() => import('Views/DataTracking')),
  },
  {
    path: `${base}/pageConfig`,
    component: loadable(() => import('Views/PageConfig')),
  },
]
export const StaticRouters = () => (
  <Switch>
    {routeMap.map((route, index) => (
      // eslint-disable-next-line react/no-array-index-key
      <Route key={index} {...route} />
    ))}
    <Redirect to={`${base}/404`} />
  </Switch>
)

And I found that the StaticRouter is () => boolean ???

error type

I have upload some of my code to codesandbox.

Upvotes: 0

Views: 232

Answers (1)

Melvynx
Melvynx

Reputation: 1145

I tried all of your code in my visual studio and I havn't your error.

Thanks for your codesandbox.

I tried some code and I found a solution that not throw an error but I don't know where did your mistake come from.

Here is my solution.

The only thing who is different is the loadable(() => import('Views/Home')) can don't match with the type of "component" props React.ComponentType<any> | React.ComponentType<RouteComponentProps<any, StaticContext, unknown>> | undefined

Upvotes: 1

Related Questions