【问题标题】:How to correctly use JSDoc with Closure Compiler to rename properties identically?如何正确使用 JSDoc 和 Closure Compiler 来相同地重命名属性?
【发布时间】:2015-10-23 16:07:43
【问题描述】:

我有一个函数,它接受类似字典的对象,并且必须提取一个特定属性并遍历可能的嵌套子对象:

function process(obj){

    //extract ID
    let secret = obj.secret;
    delete obj.secret; // yes, I have to delete that property, not just set to null

    // do some stuff

    if (Array.isArray(obj.others)) {

        // Extract others
        let others = obj.others;
        delete obj.others; // yes, I have to delete that property too

        // Process children too
        others.forEach(foo);
    }
}

我使用这个函数来处理对象:

class MyClass {

    contructor() {
        //init
    }

    getDictionary() {

        return {
            secret: 123,
            baz: 'baz',
            bar: 'bar',
            others: [{
                    secret: OtherClass,
                    forbar: 'foobar',
                    others: [{...},...]
                },{
                    ...
                }]
        };
    }

    parse() {
        return process(this.getDictionary());
    }
}

Closure Compiler 总是将 process 函数中的“obj.secret”重命名为(类似于)“aa”,但并不总是将 getDictionary 返回的对象中的“secret”属性重命名时间>。如果是这样,他们没有以相同的方式重命名“秘密”属性。

我不想导出那些 - obj['secret'] :我希望它们被重命名。我在 Closure Compiler guide 中寻找 JSDoc 注释,但我不知道该怎么做。

特别是如何定义字典,它具有强制性的“秘密”属性(类型:数字或某个类)、可选的“其他”属性(相同结构的字典数组)和零个或多个字符串属性。

【问题讨论】:

    标签: google-closure-compiler jsdoc


    【解决方案1】:

    您有 2 个选项:

    禁用基于类型的优化

    设置--use_types_for_optimization=false 标志。任何同名的属性都会被一致地重命名——无论它们看起来是否相关。

    实现一个接口

    为编译器提供足够的类型信息,以便它识别出相关的属性并且必须一致地重命名:

    /** @interface */
    function MyDictionary() {}
    
    /** @type {number} */
    MyDictionary.prototype.secret;
    
    /** @type {MyDictionary} */
    MyDictionary.prototype.others;
    

    然后将类型注释添加到您的其他代码中:

    /** @return {MyDictionary} */
    getDictionary() { ... }
    
    /** @param {MyDictionary} obj */
    function process(obj){ ... }
    

    您可能还需要对 getDictionary 方法返回的对象进行类型转换。

    【讨论】:

      猜你喜欢
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      相关资源
      最近更新 更多