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

React 16迁移18时ComponentType类型扩展无效,重命名即生效求助

React 16迁移至React 18时扩展ComponentType类型失效问题

开发React 16到18的兼容层时,尝试扩展React的ComponentType类型,但自定义的扩展未被读取,仍使用React类型定义中的默认ComponentType。将导出类型名改为ComponentType2则可正常工作,说明类型文件已被正确引入。

相关代码

src/types/react.d.ts

import * as React from "react";

type ComponentTypeCompat<P> = React.ComponentType<
  P & {
    children: React.ReactNode;
  }
>;

declare module "react" {
  type ComponentType<P = {}> = ComponentTypeCompat<P>; // <-- 此代码被忽略
  type ComponentType2<P = {}> = ComponentTypeCompat<P>; // <-- 此代码生效
}

src/components/OldComponent.tsx

import { ComponentType } from "react";

export const OldComponent: ComponentType<{ value: number }> = (props) => {
  return (
    <div>
      {props.value}
      {props.children} /* 抛出类型错误,props中缺少children */
    </div>
  );
};

src/components/OldComponent2.tsx

import { ComponentType2 } from "react";

export const OldComponent2: ComponentType2<{ value: number }> = (props) => {
  return (
    <div>
      {props.value}
      {props.children} /* 正常工作,识别children为ReactNode类型 */
    </div>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:13:32