流类型检查:即使有条件,undefined 也不是函数

Flow type checking: undefined is not a function even if there is a conditional

我正在使用 Flow 作为我的 JavaScript 代码的静态类型检查器,但出现以下错误:

Cannot call this.props.onChange because undefined [1] is not a function.
 [1]  25│     onChange?: Time => any,
        :
     192│         if (isValid && this.props.onChange) {
     193│             const match = this.matchValue(value);
     194│             if (match) {
     195│                 this.props.onChange(this.parsedToTime(this.parseValue(match)));
     196│             }
     197│         }
     198│     }

我对 Props 的定义是这样的(定义了更多的 props,标有 ...):

type Props = {
    ...
    onChange?: Time => any,
    ...
};

然后我在我的 React class 定义中使用 props 作为类型参数:

export default class TimeInput extends React.Component<Props, State> {
    ...

    // ...and in this class I have a method that calls onChange
    //    if onChange is not evaluated as false

    handleChange = ({ target }: { target: { value: string } }) => {
        const { value } = target;
        const isValid = this.validateInput(value);

        this.setState({
            value,
            isValid
        });

        if (isValid && this.props.onChange) {
            const match = this.matchValue(value);
            if (match) {
                this.props.onChange(this.parsedToTime(this.parseValue(match)));
            }
        }
    };
}

如果我正确理解 Flow Docsif (this.props.onChange) {...} 测试应该足以让 Flow 理解,onChange 不能是 undefined 因此它必须是函数(在类型定义中定义)。

我做错了什么?

根据流程文档,尤其是 "refinement invalidation" section,您应该在调用之前检查 if (this.props.onChange)

我还假设指定 defaultProps 就像 onChange: () => {} can be a better workaround 因为在调用回调之前你得到的检查较少。