首页 > 解决方案 > 流类型检查:即使有条件,undefined 也不是函数

问题描述

我使用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 类定义中使用 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 Docs,那么if (this.props.onChange) {...}测试应该足以让 Flow 理解,那onChange不可能,undefined因此它必须是一个函数(如类型定义中所定义)。

我在这里做错了什么?

标签: javascriptreactjsflowtype

解决方案


直到流程文档,尤其是“细化失效”部分if (this.props.onChange),您应该在调用之前进行检查。

此外,我假设指定defaultPropslikeonChange: () => {} 可能是一个更好的解决方法,因为在调用回调之前你得到的检查更少。


推荐阅读