javascript - 流类型检查:即使有条件,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
因此它必须是一个函数(如类型定义中所定义)。
我在这里做错了什么?
解决方案
直到流程文档,尤其是“细化失效”部分if (this.props.onChange)
,您应该在调用之前进行检查。
此外,我假设指定defaultProps
likeonChange: () => {}
可能是一个更好的解决方法,因为在调用回调之前你得到的检查更少。
推荐阅读
- amazon-web-services - AWS IoT Core 和移动 SDK - 缓存容量和缓存控制?
- jquery - 在可变持续时间内缩小 div 的宽度
- r - 在每个 facet_wrap 中包含所有数据的绘图
- hl7-fhir - URL 中 FHIR 资源名称的大小写
- ubuntu-16.04 - E: 包 'oracle-java8-installer' 没有安装候选
- laravel - 找不到 Orchestra 测试台
- java - 递归搜索房间数组列表中的路径
- workflow - 如何将 UIPath Workflow 转换为 Activity 或创建自定义 Activity?
- java - 如何修复android中的“无法访问android.support.v4.app.ActivityCompat not found的ActivityCompat类文件”错误?
- java - 如何在 Java 编程中修复“线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常”