我收到“算术运算的操作数必须是数字”的错误。但在函数开始时,我进行了运行时检查以确保 this.startedDateTime
是一个数字。我对为什么这种类型优化不起作用感到困惑。
/* @flow */
class Transfer {
startedDateTime: ?number;
start() {
this.startedDateTime = new Date().getTime();
}
get elapsedTime(): ?number {
if (typeof this.startedDateTime === 'number') {
const currentDateTime: number = new Date().getTime();
const elapsedMs: number = this.startedDateTime - currentDateTime;
return elapsedMs;
}
return null;
}
}
最佳答案
问题是类型细化在第一个后续函数调用中无效 - 在您的示例中为 Date().getTime()
。
函数/方法不是纯粹的 Javascript,但可能会产生副作用。 Date().getTime()
例如可以删除 this.startedDateTime
或将其设置为 null
。因此,流程会使您的细化无效以保持类型安全。
要绕过此行为,您可以在任何函数调用之前将属性存储在常量中:
/* @flow */
class Transfer {
startedDateTime: ?number;
start() {
this.startedDateTime = new Date().getTime();
}
get elapsedTime(): ?number {
if (typeof this.startedDateTime === 'number') {
const startedDateTime = this.startedDateTime;
// ^^^^^^^^^^^^^^^^^^^^^
const currentDateTime: number = new Date().getTime();
const elapsedMs: number = startedDateTime - currentDateTime;
// ^^^^^^^^^^^^^^^
return elapsedMs;
}
return null;
}
}
关于javascript - Flow 中的类型优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47036962/