Search code examples
reactjstypescriptdefinitelytypedmodule-augmentation

using react v18 with Typescript < v5.1, while allowing string as valid JSX Element


Full reproducible repo is https://github.com/Liooo/vite-project, just run yarn install && yarn tsc to see the error.

I want to use react v18 with Typescript < v5.1, but tsc raises error TS2786 'MyComponent' cannot be used as a JSX component. Its return type 'string' is not a valid JSX element. like below:

const MyComponent = () => 'x'

function App() {
  return (
    <>
      <div>
        <MyComponent />
       // ↑
        // error TS2786: 'MyComponent' cannot be used as a JSX component.
        //     Its return type 'string' is not a valid JSX element.
      </div>
    </>
  )
}
// package.json
{

  "dependencies": {
    "react": "^18.3.1",
    "react-dom": "^18.3.1"
  },
  "devDependencies": {
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "typescript": "4.9.5" // <= the error disappears with for example "5.1.6"
  }
}

When I update typescript to > v5.1, the error disappears.

Tried tweaking JSX.Element augmentation like these but no luck so far.

to be precise, my goal here is the following:

  1. use react@v18
  2. use [email protected]
  3. allow string (and other ReactNode-ish types) as valid JSX Element

Notes:

Wrapping strings in elements like const MyComponent = () => (<>{'x'}</>) works, but don't wanna do this, wanna be able to return string from component)

The error should be related to this microsoft/Typescript issue


Solution

  • There's no workaround except upgrading typescript:

    https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/69919#discussioncomment-9892117