Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.Lazy usage throws "Expression produces a union type that is too complex to represent"

I am trying to develop a simple application with two different components. The main one uses React.lazy to get the other component and wraps it inside a React.Suspense element. But there is a super weird error in this simple example and a more abnormal hacky solution.

The error is:

Expression produces a union type that is too complex to represent

The source code is below. And I also created a repository that you can easily repeat the error yourself.

App.tsx contents

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);

As you can see, App.tsx imports ./Fragment with React.lazy. And when using the Fr component, Typescript throws the error.

Fragment.tsx contents

import * as React from "react"

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

export default Fragment

When using Typescript 4.1.2, it works without any error, but in 4.5.2, it is not.

Weird Solution

When you uncomment the dummy assignment const dummy = <Fr />, it works without any problem.

Now, I am wondering what is the actual problem here and why the dummy assignment solves it.

like image 775
Ahmet Can Güven Avatar asked Oct 29 '25 05:10

Ahmet Can Güven


1 Answers

I bumped into this issue and managed to fix it by updating the compilerOptions.lib option in the tsconfig.json file from ["ES2015"] to ["DOM", "DOM.Iterable", "ESNext"].

like image 122
Zain Avatar answered Oct 30 '25 22:10

Zain