You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React 18搭配TypeScript<5.1时允许字符串作为JSX元素的方案问询

解决React 18 + TypeScript <5.1 中组件返回字符串的TS2786错误

问题复现

执行yarn install && yarn tsc即可触发错误:

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" // 升级到5.1.6及以上错误自动消失
  }
}

需求目标

  • 使用react@v18
  • 使用typescript@v4.9.5
  • 允许组件直接返回字符串(及其他ReactNode类型)作为有效JSX元素,无需包裹在<>或其他容器元素中

问题背景

该错误源于TypeScript 5.1之前的版本对JSX元素类型的限制,TypeScript的PR #51328在5.1版本中修复了此问题,让ReactNode类型(包括字符串、数字、布尔值等)可以直接作为组件返回值。但在5.1以下版本需要手动扩展类型。

解决方案

在项目中创建类型声明文件(例如src/react-jsx-fix.d.ts),扩展JSX.Element类型使其兼容ReactNode:

import type { ReactNode } from 'react';

declare global {
  namespace JSX {
    interface Element extends ReactNode {}
  }
}

确保tsconfig.json包含该声明文件:

{
  "include": ["src/**/*", "src/react-jsx-fix.d.ts"]
}

完成上述修改后,TypeScript 4.9.5会将字符串等ReactNode类型视为有效的组件返回值,不再抛出TS2786错误。

内容的提问来源于stack exchange,提问作者Ryo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 18:14:52