Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Type 'Element' is not assignable to type 'ReactChildren'

I'm stuck and have no idea how to tackle this error anymore.

Here is code of my App component

const App = () => (
  <Root>
    <Layout>
      <Router history={history}>
        <Navbar />
        <Switch>
          {routingConfig.map((page: RouteElement, idx: number) => {
            const { exact, path, component } = page
            return <Route key={idx} exact={exact} path={path} component={component} />
          }
          )}
        </Switch>
      </Router>
    </Layout>
  </Root>
)

Errors I'm getting (same error happens in two components - Layout and Router):

> Type 'Element' is not assignable to type 'ReactChildren |
> (ReactChildren & string) | (ReactChildren & number) | (ReactChildren &
> false) | (ReactChildren & true) | (ReactChildren & ReactElement<...>)
> | (ReactChildren & ReactNodeArray) | (ReactChildren & ReactPortal)'.  
> Type 'Element' is not assignable to type 'ReactChildren &
> ReactPortal'.
>     Type 'Element' is missing the following properties from type 'ReactChildren': map, forEach, count, only, toArray  TS2322
> 
>     14 | const App = () => (
>     15 |   <Root>
>   > 16 |     <Layout>
>        |     ^
>     17 |       <Router history={history}>
>     18 |         <Navbar />
>     19 |         <Switch>


    15 |   <Root>
    16 |     <Layout>
  > 17 |       <Router history={history}>
       |       ^
    18 |         <Navbar />

Code of Layout component:

interface Props {
    children: React.ReactChildren
}

const Layout: React.FC<Props> = ({ children }) => <div className="layout">{children}</div>

When I added ts-ignore above Layout component different errors seems to bubble up to the Root component

Type '{ children: (string | Element)[]; }' is not assignable to type 'Props'.
  Types of property 'children' are incompatible.
    Type '(string | Element)[]' is missing the following properties from type 'ReactChildren': count, only, toArray  TS2322

    13 | 
    14 | const App = () => (
  > 15 |   <Root>
       |    ^
    16 |     //@ts-ignore
    17 |     <Layout>
    18 |       <Router history={history}>

Code of Root component:

interface Props {
    children: React.ReactChildren
}

export const Root: React.FC<Props> = ({ children }) => (
    <Provider store={store}>
        {children}
    </Provider>
)

No idea why Element type is being returned at some point there. Any hint would be appreciated.

like image 914
Mariusz S. Avatar asked Sep 17 '25 05:09

Mariusz S.


2 Answers

It looks like your Layout children props is supposed to be child or element since you have just only child:

interface Props {
  children: React.ReactChild
}
like image 132
tmhao2005 Avatar answered Sep 19 '25 20:09

tmhao2005


ReactChild is deprecated. Just use ReactNode

interface Props {
    children: React.ReactNode
}
like image 20
Jeevan Avatar answered Sep 19 '25 20:09

Jeevan