question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Type def component in router config

See original GitHub issue

Hi,

I can’t get rid of TypeScript except by typing any at one place. I need help on the following code :

/** My imports */
import loadable from '@loadable/component'
import pMinDelay from 'p-min-delay'
import React from 'react'

import Loader from '@/components/loader'

export const Home = loadable(() => pMinDelay(import(/* webpackChunkName: 'home' */ './home'), 200), {
  fallback: <Loader />
})
export const NotFound = loadable(() => pMinDelay(import(/* webpackChunkName: 'notFound' */ './not-found'), 200), {
  fallback: <Loader />
})
/** My App component, which is in fact the main router */
import '@/styles/index.scss'

import React, { ReactNode } from 'react'
import { Helmet } from 'react-helmet'
import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom'

import ErrorBoundary from '@/components/error-boundary'

import { IRoute } from './app.routes'

export interface IProperties {
  routes: IRoute[]
}

export default class App extends React.PureComponent<IProperties> {
  static defaultProps = {
    routes: [{}]
  }

  render(): ReactNode {
    const { routes } = this.props

    return (
      <>
        <ErrorBoundary>
          <Helmet defaultTitle={process.env.APP_TITLE} titleTemplate={`%s | ${process.env.APP_TITLE}`}>
            <link rel='canonical' href={process.env.SERVER_BASE_URL} />
          </Helmet>
          <Router>
            <Switch>
              {routes.map(({ component: Component, ...rest }) => (
                <Route
                  exact={rest.exact || false}
                  path={rest.path}
                  key={`${rest.name}_${rest.path}`}
                  render={routeProperties => <Component {...routeProperties} />}
                />
              ))}
              <Redirect to='/404' />
            </Switch>
          </Router>
        </ErrorBoundary>
      </>
    )
  }
}
/** My route config, here is the probleme */
import { LoadableComponent } from '@loadable/component'

import { Home, NotFound } from '@/views'

export interface IRoute {
  name: string
  exact?: boolean
  path: string
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  component: LoadableComponent<any>
}

const routes: IRoute[] = [
  {
    name: 'home',
    exact: true,
    path: '/',
    component: Home
  },
  {
    name: 'notFound',
    path: '/404',
    component: NotFound
  }
]

export default routes

How can i properly type the component: LoadableComponent<any> ?

When i try with unknown i’m getting this error on <Component /> inside my App component :

Type '{ history: History<unknown>; location: Location<unknown>; match: match<any>; staticContext?: StaticContext; }' has no properties in common with type 'IntrinsicAttributes & { fallback?: Element; } & { children?: ReactNode; }'.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:12

github_iconTop GitHub Comments

1reaction
theKasheycommented, Oct 20, 2020

React Router requires a component with RouteComponentProps as props.

Well, not quite, here is it’s defenition component?: React.ComponentType<RouteComponentProps<any>> | React.ComponentType<any>;

As a bigger example:

const X = loadable(() => import(`./Page`))
<Route component={X}/> // no error
<Route
        path="otherPath"
        render={routeProperties =>
        // @ts-expect-error 
          <X {...routeProperties} /> // expect error as long..
        }
/>

👉 Error:(20, 16) TS2559: Type ‘{ history: History<unknown>; location: Location<unknown>; match: match<any>; staticContext?: StaticContext; }’ has no properties in common with type ‘IntrinsicAttributes & { fallback?: Element; } & { children?: ReactNode; }’.

These properties really does not exists on component, and TypeScript informing you about it.


Why component is working? Because it’s not requires a component with RouteComponentProps as props. - TypeScript uses structutal types (DuckTyping) and requires component to be less than RouteComponentProps, to a subset of it, not “greater”. In other words - you can miss some properly, even all, but not add something Route is not able to provide to you.

And component accepts any as well.


I’ve also creates typescript example with react-router to reproduce this issue, and the short term goal it to compile-and-run those examples during CI.

And specifically the problem of this issue is expected. It is “correct” to have it -> https://github.com/gregberge/loadable-components/blob/master/examples/typescript/src/client/App.tsx#L24

1reaction
open-collective-bot[bot]commented, Oct 8, 2020

Hey @blephy 👋, Thank you for opening an issue. We’ll get back to you as soon as we can. Please, consider supporting us on Open Collective. We give a special attention to issues opened by backers. If you use Loadable at work, you can also ask your company to sponsor us ❤️.

<link>
Read more comments on GitHub >

github_iconTop Results From Across the Web

Routers - Spring
Spring Integration provides the following routers: Payload Type Router. Header Value Router. Recipient List Router. XPath Router (part of the ...
Read more >
How do I configure the Angular2 router that component name ...
If you want to use Router.config() , you can follow these steps: 1) In your main component, define your routes in a variable:...
Read more >
Common Routing Tasks - Angular
This topic describes how to implement many of the common tasks associated with adding the Angular router to your application.
Read more >
Developer Guide: Component Router - AngularJS: API
When we navigate to any given URL, the $rootRouter matches its Route Config against the URL. If a Route Definition in the Route...
Read more >
How to Use React Router in Typescript | Pluralsight
The above Routes are wrapped by the Router component (line 14) which will ... 1npm install --save-dev typescript @types/node @types/react ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found