类型HOC可以增强其自身属性的组件



我正在尝试使用Flow使用Recompose及其HOC类型来键入高阶组件(HOC(。

这是我的代码:

// @flow
import React from 'react';
import { compose, defaultProps, withProps, type HOC } from 'recompose';
type InnerProps = {
  text: string,
  num: number,
};
type EnhancedComponentProps = {
  text: string,
};
const baseComponent = ({ text, num }: InnerProps) => (
  <div>
    {text}
    {num}
  </div>
);
const enhance: HOC<*, EnhancedComponentProps> = compose(
  defaultProps({
    text: 'world',
  }),
  withProps(({ text }) => ({
    text: `Hello ${text}`,
  }))
);
export default enhance(baseComponent);

现在失败了:

Cannot call enhance with baseComponent bound to a because property num is missing in object type [1] but exists in
InnerProps [2] in the first argument.
     src/Text.js
 [2] 14│ const baseComponent = ({ text, num }: InnerProps) => (
       :
     27│   }))
     28│ );
     29│
     30│ export default enhance(baseComponent);
     31│
     flow-typed/npm/recompose_v0.x.x.js
 [1] 95│   ): HOC<{ ...$Exact<Enhanced>, ...BaseAdd }, Enhanced>;

尝试阅读文档和一些我无法找到解决方案的博客文章。我发现的所有例子都很微不足道,没有一个涵盖此简单的情况。

键入此代码的正确方法是什么?

我想您会遇到正确的错误。它说:

num在对象类型[1]中缺少,但在InnerProps [2]中存在 第一个参数。

您宣布您的事件将获得EnhancedComponentProps中缺少num的内容。换句话说,您尝试从只能在EnhancedComponentProps类型中声明的对象中提取num

基于重新组件的文档:您应该通过:

获得此工作
// @flow
import React from 'react';
import { compose, defaultProps, withProps, type HOC } from 'recompose';
type EnhancedComponentProps = {
  text: string,
  num: number,
};
const baseComponent = ({ text, num }: EnhancedComponentProps) => ( // in the example from recompose this typing is unnecessary though
  <div>
    {text}
    {num}
  </div>
);
const enhance: HOC<*, EnhancedComponentProps> = compose(
  defaultProps({
    text: 'world',
  }),
  withProps(({ text }) => ({
    text: `Hello ${text}`,
  }))
);
export default enhance(baseComponent);

最新更新