完整的可重现仓库是https://github.com/Liooo/vite-project,只需运行
yarn install && yarn tsc
即可查看错误。
我想将 React v18 与 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.
,如下所示:
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"
}
}
当我将 typescript 更新到 > v5.1 时,错误消失了。
尝试调整 JSX.Element 增强像这些但到目前为止还没有运气。
准确地说,我的目标是:
备注:
包裹在元素中(
MyComponent => ()=>(<>{'x'}</>)
可以工作,但不想这样做,希望能够从组件返回字符串)
该错误应该与 此 microsoft/Typescript 问题
有关只运行该函数? 为什么要尝试让函数组件返回一个字符串?
const MyComponent = (): string => { return 'x' }
...
<div>{ MyComponent() }</div>