我正在尝试用两个不同的组件开发一个简单的应用程序。主组件使用React.lazy
获取另一个组件,并将其封装在React.Suspense
元素中。但在这个简单的例子中有一个非常奇怪的错误,还有一个更不正常的破解方案。
错误为:
Expression生成的并集类型过于复杂,无法表示
源代码如下。我还创建了一个存储库,您可以自己轻松地重复错误。
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
使用React.lazy
导入./Fragment
。当使用Fr
组件时,Typescript会抛出错误。
碎片.tsx内容
import * as React from "react"
const Fragment = () => (
<div>
Fragment
</div>
)
export default Fragment
当使用Typescript 4.1.2时,它工作时没有任何错误,但在4.5.2中,它不是。
怪异的解决方案
取消对伪赋值const dummy = <Fr />
的注释时,它可以正常工作。
现在,我想知道这里的实际问题是什么,以及为什么虚拟分配能解决它
我遇到了这个问题,并通过将tsconfig.json
文件中的compilerOptions.lib
选项从["ES2015"]
更新为["DOM", "DOM.Iterable", "ESNext"]
来解决它。