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

