【问题标题】:Flow - static type checking failing流 - 静态类型检查失败
【发布时间】:2018-06-30 01:49:33
【问题描述】:

我来自 TypeScript 的世界,所以我有点不明白为什么以下没有失败。

class Bar {
  foo: string
}


let bar = new Bar();
let test = bar.foo;
test = 4; // all is good here, while it should fail!

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    您的代码没有失败,因为您基本上将变量test 定义为any。赋值时不会在变量之间传递类型。

    如果你想强制变量test 为string 类型,你应该定义它的类型。

    let test: string = bar.foo; // ok
    test = 4; // flow error
    

    这应该会引发以下错误

    ^ Cannot assign `4` to `test` because number [1] is incompatible with string [2].
    

    【讨论】:

      【解决方案2】:

      称为类属性语法https://flow.org/en/docs/types/classes/

      在你的例子中

      class Bar {
        foo: string // not defined
      }
      
      
      let bar = new Bar()
      let test = bar.foo // Copy value not type, should use let test: string = bar.foo
      test = 4
      

      【讨论】:

        猜你喜欢
        • 2021-02-28
        • 2015-01-25
        • 2015-02-08
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2014-06-08
        • 1970-01-01
        • 2014-02-18
        相关资源
        最近更新 更多