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

不修改tsconfig.json添加全局React JSX属性报ts2322错误如何解决

报错原因

  • test_a的index.d.ts顶部存在import React from 'react'语句,属于模块级声明文件,只有当代码中主动导入该模块时,TS才会加载其包含的类型定义。你当前项目没有任何地方导入test_a,因此对React HTMLAttributes的全局扩展未被TS识别生效。
  • 边缘场景:项目存在多版本@types/react,test_a依赖的@types/react版本和项目根目录安装的版本不一致,导致类型扩展合并到了其他版本的React类型定义中,未和项目实际使用的类型合并。

解决方案

方案1(推荐,无配置修改)

在项目入口文件(如index.tsx)顶部主动导入一次test_a,无需使用其导出内容,仅触发TS加载其类型声明即可:

import 'test_a'
import React from 'react';

// 此处报错消失
const test = <div test="hello" />;

方案2(适用于可维护test_a包的场景)

修改test_a的类型声明为官方推荐的模块扩展写法,无需项目侧主动导入即可自动合并类型:

// ./node_modules/test_a/index.d.ts
import type React from 'react';

declare module 'react' {
  interface HTMLAttributes<T> extends React.AriaAttributes, React.DOMAttributes<T> {
    test?: string;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:15:03