javascript - Flow 中的类型优化

标签 javascript reactjs flowtype

我收到“算术运算的操作数必须是数字”的错误。但在函数开始时,我进行了运行时检查以确保 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;
    }
}

Try it here .

最佳答案

问题是类型细化在第一个后续函数调用中无效 - 在您的示例中为 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;
  }
}

Try it

关于javascript - Flow 中的类型优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47036962/

相关文章:

javascript - 如何在react Js中使用map实现嵌套循环

javascript - 将 Angular JS 数据传递给按钮 OnClick 事件

reactjs - 如何在 JSX 中使用函数

javascript - “计算属性”可能只是流中的文字值?

typescript - typescript 的类型名称中的前缀 T 是什么意思

javascript - 在可滚动的div angularjs中滚动到顶部

javascript - 无法在 js 上填充 ddl

javascript - 在 ReactJS 上保存多个动态组件的状态

javascript - 如何让 ReactJS 呈现空的 HTML 属性

javascript - 在 Flow 中,我可以声明一个函数签名,以便我可以在任何地方重用它吗?