我正在使用 TypeScript编写React 高阶组件 (HOC)。HOC 应该比被包裹的组件多接受一个 prop,所以我写了这个:
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(我相信)是一个接受Component
. 由于我事先不知道包裹组件是什么,所以我使用泛型类型TChildProps
来定义包裹组件的 props 的形状。该函数还返回一个Component
. 返回的组件接受包装组件的 props(同样,使用 generic 类型TChildProps
)和它自己需要的一些 props(type HocProps
)。使用返回的组件时,应提供所有props(包括HocProps
包装的propsComponent
)。
现在,当我尝试使用我的 HOC 时,我会执行以下操作:
// outside parent component
const WrappedChildComponent = hoc()(ChildComponent);
// inside parent component
render() {
return <WrappedChild
thingy={ 42 }
// Prop `foo` required by ChildComponent
foo={ 'bar' } />
}
但是我收到一个typescript错误:
TS2339: Property 'foo' does not exist on type 'IntrinsicAttributes & HocProps & {} & { children? ReactNode; }'
在我看来,typescript不更换TChildProps
用的props所需要的形状ChildComponent
。我怎样才能让 TypeScript 做到这一点?