我正在写一个反应高阶组件(HOC) https://facebook.github.io/react/docs/higher-order-components.html使用 TypeScript。 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(同样,使用通用类型键入TChildProps
) and它本身需要一些道具(类型HocProps
)。当使用返回的组件时,所有的 props(都HocProps
以及包裹的道具Component
)应提供。
现在,当我尝试使用 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
与所需道具的形状ChildComponent
。我怎样才能让 TypeScript 做到这一点?
聚会有点晚了。
我喜欢使用 Omit TypeScript 实用程序类型来解决这个问题。
文档链接:https://www.typescriptlang.org/docs/handbook/utility-types.html#omitk https://www.typescriptlang.org/docs/handbook/utility-types.html#omittk
import React, {ComponentType} from 'react';
export interface AdditionalProps {
additionalProp: string;
}
export function hoc<P extends AdditionalProps>(WrappedComponent: ComponentType<P>) : ComponentType<Omit<P, 'additionalProp'>> {
const additionalProp = //...
return props => (
<WrappedComponent
additionalProp={additionalProp}
{...props as any}
/>
);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)