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
相关产品推荐
相关产品推荐

