React.cloneElement类型报错:{foo:number}与Partial<Child>&Attributes无共同属性
问题分析与解决方案
这个报错不是TypeScript的bug,而是你对旧版本@types/react的类型定义理解有偏差,咱们一步步拆解清楚:
错误根源
在你使用的@types/react@16.3.14版本里:
React.ReactElement的泛型参数应该对应组件的Props类型,而不是组件类本身- 你在
cloneChild方法里写了React.ReactElement<Child>,这里的Child是组件类,TypeScript会把它解析为组件实例的类型(包含组件的state、方法等内部属性),而非组件接收的props类型 - 对应到
React.cloneElement<Child>(child, newProps),第二个参数的类型被推断为Partial<Child>(组件实例的部分属性),但你传入的{ foo: number }是Props的结构,两者完全不匹配,所以触发类型报错
修复方案
只需要把泛型参数从组件类Child换成组件的Props类型Props即可,两处地方需要修改:
- 修正
cloneChild的参数类型:把React.ReactElement<Child>改为React.ReactElement<Props> - 修正
React.cloneElement的泛型参数:从<Child>改为<Props>
修改后的完整代码:
import * as React from "react"; interface Props { foo: number; } class Child extends React.Component<Props> { public render(): React.ReactNode { return <span>{this.props.foo}</span>; } } class Parent extends React.Component<Props> { public render(): React.ReactNode { return React.Children.map(this.props.children, (child: JSX.Element) => this.cloneChild(child)); } public cloneChild(child: React.ReactElement<Props>): React.ReactElement<Props> { const newProps = { foo: this.props.foo, }; return React.cloneElement<Props>(child, newProps); } }
额外说明
如果你升级到较新的@types/react版本(比如16.8及以上),类型定义做了优化,React.ReactElement的泛型支持直接传入组件类(通过ComponentProps等工具类型自动推导Props),写法会更灵活,但在你当前的旧版本里,必须严格使用Props类型作为泛型参数。
内容的提问来源于stack exchange,提问作者wulftone
相关产品推荐
相关产品推荐

