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:
- use react@v18
- use [email protected]
- 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
2
Answers
There's no workaround except upgrading typescript:
https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/69919#discussioncomment-9892117
just run the function?
Why try to make functional component return a string?
apparently I need to change function name to make it clear I’m not suggesting a FC as a solution but a regular function that returns a string. If the real use case resulted in a expensive re-render, hoist it, bind it to a const, memoize it.