【问题标题】:dynamic type tests not working as expected动态类型测试未按预期工作
【发布时间】:2016-07-20 19:27:53
【问题描述】:

这是SSCCE

我有一个地图容器类,其中使用第一个被调用的set 方法按需创建内部Map

// @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) 检查合并为一个:

// @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

……这对于第 19 行的访问毫无意义:

this.map.set(key,value)

… 仍被支票覆盖:

if (this.map!=null)

什么给了?

【问题讨论】:

    标签: flowtype


    【解决方案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;
        }
    }    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 2021-03-21
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      相关资源
      最近更新 更多