打字稿HOC-在React组件上需要一个道具

时间:2019-10-17 18:41:38

标签: typescript

啊,TS。我在强制HOC要求使用它的所有组件包括属性时遇到麻烦。这就是我所拥有的:

.combineLatest

用法示例:

caOrCoCities$: Observable<City[]>;

...

const californiaRef = this.angularFirestore
    .collection("cities", ref => ref.where("state","==","CA"));
const coloradoRef = this.angularFirestore
    .collection("cities", ref => ref.where("state","==","CO"));

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

1 个答案:

答案 0 :(得分:1)

这似乎可行

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