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

TypeScript提示'JSX' is not defined错误,如何给函数指定children属性为JSX元素类型?

解决步骤

1. 修复'JSX' is not defined报错

该报错通常由TypeScript配置缺失导致,按以下两个方向排查即可:

  • 确认项目已安装React类型声明依赖,缺失的话执行对应安装命令:
    # npm
    npm install @types/react @types/react-dom -D
    # yarn
    yarn add @types/react @types/react-dom -D
    # pnpm
    pnpm add @types/react @types/react-dom -D
    
  • 检查tsconfig.json配置,确认compilerOptions下的jsx字段已正确配置,React17及以上版本设为react-jsx,低版本React设为react即可:
    {
      "compilerOptions": {
        "jsx": "react-jsx",
        // 其余原有配置保持不变
      }
    }
    

配置完成后重启编辑器的TypeScript服务即可消除该报错。

2. 定义children入参类型

要声明children属性为JSX元素/JSX元素数组,推荐两种成熟写法:

写法1:使用React内置PropsWithChildren类型(最简便)

该类型会自动内置children的合法类型声明,无需手动编写:

import type { PropsWithChildren } from 'react'

// 尖括号内填写除children外的其他props类型
type ComponentProps = PropsWithChildren<{
  title?: string
  className?: string
}>

const YourComponent = (props: ComponentProps) => {
  return <div>{props.children}</div>
}

写法2:手动声明类型

如果要自定义children类型,直接用React.ReactNode即可,它本身已经覆盖了JSX元素、JSX元素数组、字符串、数字等所有React合法可渲染类型,完全满足需求:

type ComponentProps = {
  children?: React.ReactNode
  // 其余props类型
}

如果确实需要严格限制仅支持JSX元素/数组,可以写为children?: React.ReactElement | React.ReactElement[],不过该写法会限制字符串、数字等合法子元素的传入,非特殊需求不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:54:03