动态类型测试未按预期工作

时间:2016-07-20 11:00:20

标签: flowtype

这是SSCCE

我有一个地图容器类,其中根据需要创建内部cplt_flag,并调用第一个1方法:

Map

上面的代码通过了set而没有任何警告。

但是,如果我将两个// @flow 'use strict'; class MapContainer { map: ?Map<any, any>; constructor() { this.map=null; } set(key: any, value: any): ?any { if (this.map===null) { this.map = new Map(); } let prevValue: ?any; if (this.map!=null) { // first check prevValue = this.map.get(key); } if (this.map!=null) { // second check this.map.set(key, value); } return prevValue; } } exports.MapContainer = MapContainer; 支票合并为一个:

npm run flow

...然后运行流程失败并显示以下消息:

if (this.map!=null)

......作为第19行的访问根本没有意义:

// @flow 'use strict'; class MapContainer { map: ?Map<any, any>; constructor() { this.map=null; } set(key: any, value: any): ?any { if (this.map===null) { this.map = new Map(); } let prevValue: ?any; if (this.map!=null) { // merged check prevValue = this.map.get(key); this.map.set(key, value); } return prevValue; } } exports.MapContainer = MapContainer;

......仍然由支票覆盖:

es6/map-container.js:19 19: this.map.set(key, value); ^^^^^^^^^^^^^^^^^^^^^^^^ call of method `set`. Method cannot be called on possibly null value 19: this.map.set(key, value); ^^^^^^^^ null es6/map-container.js:19 19: this.map.set(key, value); ^^^^^^^^^^^^^^^^^^^^^^^^ call of method `set`. Method cannot be called on possibly undefined value 19: this.map.set(key, value); ^^^^^^^^ undefined

是什么给出了?

1 个答案:

答案 0 :(得分:1)

问题是调用get方法会使细化无效。如果getthis.map设置为null,该怎么办? Flow无法知道,因此它假设最糟糕。您可以这样做:

class MapContainer {

    map: ?Map<any, any>;

    constructor() {
        this.map=null;
    }

    set(key: any, value: any): ?any {     
        if (!this.map) {
            this.map = new Map();
        }

        const map = this.map;

        let prevValue: ?any;
        if (this.map!=null) {
            prevValue = map.get(key);
            map.set(key, value);
        }
        return prevValue;
    }
}