我正在 用TypeScript 写一个React高阶组件(HOC)。HOC应该比包装的 组件接受更多的道具,所以我这样写:
type HocProps { // Contains the prop my HOC needs thingy: number } type Component<P> = React.ComponentClass<P> | React.StatelessComponent<P> interface ComponentDecorator<TChildProps> { (component: Component<TChildProps>): Component<HocProps & TChildProps>; } const hoc = function<TChildProps>(): (component: Component<TChildProps>) => Component<HocProps & TChildProps) { return (Child: Component<TChildProps>) => { class MyHOC extends React.Component<HocProps & TChildProps, void> { // Implementation skipped for brevity } return MyHOC; } } export default hoc;
换句话说,hoc是产生实际HOC的函数。(我相信)此HOC是接受a的函数Component。由于我事先不知道被包装的组件是什么,因此我使用泛型类型TChildProps来定义被包装的组件的道具形状。该函数还 返回Component。返回的组件接受包装组件的道具(再次,使用generic键入TChildProps),并 为其自身需要一些道具(类型HocProps)。使用返回的组件时,应提供所有道具(包括HocProps包装好的道具Component)。
hoc
HOC
Componen
TChildProps
Component
generic
HocProps
现在,当我尝试使用HOC时,请执行以下操作:
// outside parent component const WrappedChildComponent = hoc()(ChildComponent); // inside parent component render() { return <WrappedChild thingy={ 42 } // Prop `foo` required by ChildComponent foo={ 'bar' } /> }
But I get a TypeScript error:
TS2339: Property 'foo' does not exist on type 'IntrinsicAttributes & HocProps & {} & { children? ReactNode; }'
在我看来TypeScript并没有替换TChildProps为所需的道具的形状ChildComponent。如何使TypeScript做到这一点?
ChildComponent
TypeScript
我找到了一种使其工作的方法:通过使用hoc提供的type参数调用 ,如下所示:
type
import ChildComponent, { Props as ChildComponentProps } from './child'; const WrappedChildComponent = hoc<ChildComponentProps>()(ChildComponent);
但我不是很喜欢。它要求我导出孩子的道具 (我宁愿不这样做),我 有种感觉,我正在告诉TypeScript 它应该能够推断出的东西。