TypeScript - 类型“Element”不可分配给类型“ReactChildren”

Mar*_* S. 4 javascript typescript reactjs react-router

我被困住了,不知道如何解决这个错误了。

这是我的应用程序组件的代码

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>
)
Run Code Online (Sandbox Code Playgroud)

我收到的错误(同样的错误发生在两个组件中 - 布局和路由器):

> 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 />
Run Code Online (Sandbox Code Playgroud)

布局组件代码:

interface Props {
    children: React.ReactChildren
}

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

当我在布局组件上方添加 ts-ignore 时,不同的错误似乎会冒泡到根组件

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}>
Run Code Online (Sandbox Code Playgroud)

根组件代码:

interface Props {
    children: React.ReactChildren
}

export const Root: React.FC<Props> = ({ children }) => (
    <Provider store={store}>
        {children}
    </Provider>
)
Run Code Online (Sandbox Code Playgroud)

不知道为什么在某个时候会返回 Element 类型。任何提示将不胜感激。

tmh*_*005 7

看起来你的Layout孩子道具应该是孩子或元素,因为你只有一个孩子:

interface Props {
  children: React.ReactChild
}
Run Code Online (Sandbox Code Playgroud)