【问题标题】:React.Lazy usage throws "Expression produces a union type that is too complex to represent"React.Lazy 用法抛出 \"Expression produces a union type that is too complex to represent\"
【发布时间】:2022-12-09 13:53:00
【问题描述】:

我正在尝试开发一个包含两个不同组件的简单应用程序。 主要的使用 React.lazy 获取另一个组件并将其包装在 React.Suspense 元素中。但是在这个简单的例子中有一个超级奇怪的错误和一个更变态的hacky解决方案。

错误是:表达式产生的联合类型太复杂而无法表示

源代码如下。而且我还创建了一个repository,您可以轻松地自己重复错误。

App.tsx 内容

import React from "react"
import ReactDom from "react-dom"

const Fr = React.lazy(
    () => import('./Fragment')
);

// Uncomment this line below, then it compiles without any errors
// const dummy = <Fr />

const Main = () => (
    <div>
        <React.Suspense fallback={"Loading"}>
            <div>
                <Fr/> {/* Error:  Expression produces a union type that is too complex to represent */}
            </div>
        </React.Suspense>
    </div>
)

// @ts-ignore
ReactDom.render(<Main/>, document.body);

如您所见,App.tsx 导入 ./FragmentReact.lazy。当使用 Fr 组件时,打字稿会抛出错误。

Fragment.tsx 内容

import * as React from "react"

const Fragment = () => (
    <div>
        Fragment
    </div>
)

export default Fragment

使用 Typescript 4.1.2 时,它没有任何错误,但在 4.5.2 中,却没有。

奇怪的解决方案

当您取消注释虚拟分配 const dummy = &lt;Fr /&gt; 时,它可以正常工作。

现在我想知道这里的实际问题是什么以及为什么虚拟分配可以解决它?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    我得到完全相同的错误,等待解释和解决方案。我的ts版本是4.8.4

    【讨论】:

      猜你喜欢
      • 2018-03-24
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 2022-12-02
      • 2022-12-02
      • 1970-01-01
      • 2012-02-03
      相关资源
      最近更新 更多