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

使用TypeScript检查React函数组件JS代码遇TS2607/TS2786错误求助

React函数组件TypeScript类型检查报错TS2607/TS2786的解决办法

问题描述

使用TypeScript对带有文档字符串类型注解的JavaScript代码做类型检查,原本一切正常,但引入React后出现异常:类组件写法(export default class MyComponent extends React.Component {...})无问题,但改用函数组件写法(export default function MyComponent(props) {...})后,每个组件都会触发TS2607和TS2786错误。

错误信息

src/apps/status/App.js:37:21 - error TS2607: JSX element class does not support attributes because it does not have a 'props' property.

37                     <ServerTable
                       ~~~~~~~~~~~~
38                         srvData={srvData}
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
39                     />


src/apps/status/App.js:37:22 - error TS2786: 'ServerTable' cannot be used as a JSX component.
  Its instance type 'ServerTable' is not a valid JSX element.
    Type 'ServerTable' is missing the following properties from type 'ElementClass': render, context, setState, forceUpdate, and 3 more.

37                     <ServerTable
                        ~~~~~~~~~~~

相关代码及配置

ServerTable.js

import PropTypes from "prop-types";
import React from "react";

import LocationRow from "@apps/status/LocationRow.js";


/** @typedef {import('@types').ServerTablePropTypes} ServerTablePropTypes */

/**
 *
 * @param {ServerTablePropTypes} props
 * @returns {JSX.Element}
 * @constructor
 */
export default function ServerTable(props) {
    return <table className="server">
        <tbody>
        {Object.entries(props.srvData.locations).sort().map(
            ([locName, locData], _i) =>
                <LocationRow
                    key={locName}
                    locName={locName}
                    locDescription={locData.description}
                />
        )}
        </tbody>
    </table>;
}


ServerTable.propTypes = {
    srvData: PropTypes.object.isRequired,
};

types.ts

...

export type ServerTablePropTypes = {
    srvData: {locations: object},
};

类型检查命令:npx tsc --build jsconfig.json

解决办法

1. 移除JSDoc中的@constructor标签

函数组件不是构造函数,@constructor注解会误导TypeScript将其识别为类组件,引发类型不匹配。修改后的JSDoc如下:

/**
 * @param {ServerTablePropTypes} props
 * @returns {JSX.Element}
 */

2. 修正jsconfig.json的JSX配置

确保配置中正确指定React的JSX处理模式,示例配置:

{
  "compilerOptions": {
    "jsx": "react",
    "checkJs": true,
    "strict": true,
    "types": ["react", "prop-types"]
  },
  "include": ["src/**/*"]
}
  • jsx: "react":告知TypeScript按React规则解析JSX
  • checkJs: true:启用JavaScript文件的类型检查
  • types:确保React和PropTypes的类型定义被加载

3. 安装完整的类型依赖

检查package.json,确保已安装@types/react和@types/prop-types,若未安装则执行:

npm install --save-dev @types/react @types/prop-types

错误原因

TS2607和TS2786的本质是TypeScript误将函数组件识别为类组件。类组件需要继承React.Component并具备render、setState等方法,而函数组件是纯函数,不具备这些特性,因此触发“缺少ElementClass属性”的校验错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:06:29