React 19 TypeScript自定义Web Component类型失效问题修复咨询
React 19 中适配 Web Component 的 JSX 类型定义修复方案
问题说明
在 React 18 中,通过全局声明 JSX.IntrinsicElements 可正常适配自定义 Web Component 的类型,但升级到 React 19 后,该类型定义不再生效,尽管相关类型仍能全局访问。
修复方案
React 19 对 Web Component 的类型处理逻辑做了调整,需按以下方式修改类型声明:
- 修正拼写错误:原代码中
custom-compoenent存在拼写错误,应为custom-component,这是导致类型不生效的基础问题之一。 - 调整 JSX 类型声明结构:React 19 无需嵌套
DetailedHTMLProps,直接使用React.HTMLAttributes<CustomComponent>即可完成类型映射;也可借助HTMLElementTagNameMap的关联关系简化定义。
修正后的完整代码
declare global { class CustomComponent extends HTMLElement { // 可在此添加组件的属性、方法类型定义 } interface HTMLElementTagNameMap { "custom-component": CustomComponent; } namespace JSX { interface IntrinsicElements { // 方式1:直接使用 HTMLAttributes 完成类型映射 "custom-component": React.HTMLAttributes<CustomComponent>; // 方式2:借助已有元素类型扩展(适合需要复用基础属性的场景) // "custom-component": React.JSX.IntrinsicElements["div"] & { // // 自定义属性可在此补充 // customProp?: string; // }; } } } export {}; // 确保文件为模块,避免全局声明冲突
关键注意点
- React 19 优化了 Web Component 的类型推断逻辑,直接使用
React.HTMLAttributes<T>即可正确映射组件的原生属性与事件类型。 - 全局声明必须放在模块文件中(即包含
export {}或其他导出语句),否则 TypeScript 无法正确识别这些声明。 - 若自定义组件有额外的自定义属性/事件,可在
IntrinsicElements的对应接口中补充,示例:"custom-component": React.HTMLAttributes<CustomComponent> & { customProp: string; onCustomEvent: (event: CustomEvent) => void; };
内容的提问来源于stack exchange,提问作者Dust shooter
相关产品推荐
相关产品推荐

