javascript - Flowtype:不安全的实例变量访问

标签 javascript ecmascript-6 flowtype es6-class

/* @flow */

class Foo {
    blah: string;
    bar: string;
    constructor(blah: string, bar?: string) {
            this.blah = blah
            if (bar) {
                this.bar = bar
            }
    }
}

const foo = new Foo('okok')
foo.bar

https://flowtype.org/try/#0PQKgBAAgZgNg9gdzCYAoVBjGBDAzrsAMTjjAG9UBIAI2wCcAuMXAFzoEsA7AcwG5UAvugxxOrMFBJgAvGE4BTJMTgAKAJSpJcAHS06QA

这不会引发流类型错误吗?

编辑:

这可能回答我的问题...

https://flowtype.org/docs/nullable-types.html#undefined-values-and-optional-types

Undefined Values and Optional Types Undefined values, just like null, can cause issues too. Unfortunately, undefined values are ubiquitous in JavaScript and it is hard to avoid them without severely affecting the usability of the language. For example, arrays can have holes for elements; object properties can be dynamically added and removed. Flow ignores the possibility of undefined resulting from object property and array element accesses. Being stricter would force the programmer to do undefined checks (like null checks) on each dereference of an array element or object property to get anything useful done.

However, Flow does detect undefined local variables and return values, and it considers optional parameters and properties to possibly be undefined. As such, uses of these types must be guarded by undefined checks to avoid errors.

最佳答案

当前 (v0.36) 类字段不受 Flow 确保

class Foo {
  bar: string;
}

new Foo().bar // no error

关于javascript - Flowtype:不安全的实例变量访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41010193/

相关文章:

javascript - JQuery event.target 错误

javascript - 如何使用 JS 匹配检查字符串中所有可能的大小写?

javascript - 从 angular v2.0.0.0-alpha.22.ts 内部理解第一行(列表与数组)

javascript - 如何创建只能包含流中某些属性的类型?

javascript - 通过ajax提交表单不起作用

javascript - 将信息传递到 jQuery ajax 响应处理函数中

javascript - 函数参数测试类型

javascript - 如何在 Adob​​e XD 插件中使用 ES6 模块?

javascript - 可选(选择性)流程检查

reactjs - FlowType - 推断 React 组件的通用类型