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

React TypeScript中如何为接收函数组件的Prop定义类型

React组件接收带children的函数组件Prop的类型修正

原代码

interface ComponentBProps {
  someComponent?: React.ComponentType;
  msg: string;
}

function ComponentB({someComponent: SomeComponent, msg}: ComponentBProps ) {
  return (
    <div>
      {
        SomeComponent && <SomeComponent>
          <div>
            {msg}
          </div>
        </SomeComponent>
      }
    </div>
  );
}

function ComponentA() {
  return (
    <ComponentB
      someComponent={({children}) => <div>{children}</div>}
      msg="msg"
    />
  );
}

报错信息

Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'.
Property 'children' does not exist on type '{}'.

解决方案

将ComponentBProps中的someComponent类型修改为:

someComponent?: React.ComponentType<{ children: React.ReactNode }>;

原因说明

  • React.ComponentType默认泛型参数为空对象{},不包含children属性的类型声明,当给组件传递children时,TypeScript无法识别该props的合法性,因此抛出类型错误。
  • 显式指定泛型参数为{ children: React.ReactNode },明确告知TypeScript这个组件接收children作为props,即可解决类型不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:50:31