首页 > 解决方案 > 使用导入的函数时,流不会推断类型细化

问题描述

我有一个使用 Flow 输入的 React 组件:

import { isFunction } from './utils';

type Props = {
  ...
  onRemove?: Function,
};

class MyComponent extends React.Component<Props> {
  render() {
    // ...
  }

  _handleRemove = () => {
    if (isFunction(this.props.onRemove)) {
      this.props.onRemove();
    }
  }
}

这是我的isFunction实用程序:

export function isFunction(value: any): boolean %checks {
  return typeof value === 'function';
}

Flow 在检查我的代码时抛出以下错误:

Cannot call onRemove because undefined [1] is not a function.

省略 util 函数并简单地使用typeof this.props.onRemove === 'function'或将函数定义移动到组件文件中修复了错误,但我显然希望能够在我的代码库中使用 util 函数。

是我做错了什么还是 Flow 在使用导入时有问题?如果是后者,是否有已知的解决方法?

标签: reactjsflowtype

解决方案


推荐阅读