首页 > 解决方案 > Typescript HOC - 需要 React 组件上的道具

问题描述

啊,TS。我无法强制 HOC 要求所有使用它的组件包含属性。这就是我所拥有的:

interface ExpectedComponentProps {
    requiredProp: string;
    [other: string]: any;
}

const withRequiredProp = function<OriginalProps extends ExpectedComponentProps>(
    WrappedComponent: React.ComponentType<OriginalProps>
) {
    // here I know requiredProp is defined for the component
}

示例用法:

const MyNewComponent = withRequiredProp(MyComponent);

// this should be valid
// <MyNewComponent requiredProp="hello" />

// this should throw a TS error
// <MyNewComponent />

但是,它并没有像我期望的那样强制执行 requiredProp 。我怎么弄乱了这里的语法?

标签: typescript

解决方案


这似乎有效

function withRequiredProp<C extends React.ComponentType<any>>(
  Component: C,
): React.ComponentType<ExpectedComponentProps> {
  return Component //we just return the argument but we said it was 
  // React.ComponentType<ExpectedComponentProps>
}

const MyComponent: React.FC = () => (
  <div>test</div>
);

const MyNewComponent = withRequiredProp(MyComponent);

现在,MyComponent不强制执行 requiredProp。但MyNewComponent确实如此。

<MyComponent /> //OK
<MyNewComponent /> //error
<MyNewComponent requiredProp="hello" /> //OK

推荐阅读