【问题标题】:Type Refinements in Flow流中的类型改进
【发布时间】:2017-11-01 05:00:37
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs flowtype


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      在您的方法中,startedDateTime 可以是:numbernullundefined,因为您使用的是 Flow Maybe Types。你只需要说:startedDateTime: number;

      你是example

      也许你想这样做:

      class Transfer {
          startedDateTime: ?number;
          start() {
              return this.startedDateTime = new Date().getTime();
          }
          get elapsedTime(): ?number {
              if (typeof this.startedDateTime === 'number') {
                  const currentDateTime: number = new Date().getTime();
                  const elapsedMs: number = this.start() - currentDateTime;
                  return elapsedMs;
              }
              return null;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-03
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 2011-05-21
        相关资源
        最近更新 更多