How can I prevent the warning 'Property MyProp1 never defined on MyObject'?

后端 未结 5 1948
既然无缘
既然无缘 2021-01-11 10:43

I have some HTML that contains a JSON string. In the on DOM ready callback, I have something like this:

MyObject = JSON.parse($(\'#TheJsonString\').         


        
5条回答
  •  温柔的废话
    2021-01-11 11:10

    The cleanest way to remove the warning is by defining the structure of the JSON. This can be done using the @type tag:

    /** @type {{MyProp1:string}} */
    

    Where MyProp1 is the name of the property, and string is the type.

    Google's Closure compiler will rename the variable. If you don't want that, you have to use quotes + brackets instead of the dot-notation:

    MyObject['MyProp1']
    

    Example: paste the following in the Closure Compiler:

    // ==ClosureCompiler==
    // @compilation_level ADVANCED_OPTIMIZATIONS
    // ==/ClosureCompiler==
    
    var MyObject;
    function x() { // Magic happens at the next line
        /** @type {{MyProp1:string}}*/
        MyObject = JSON.parse(prompt(''));
    }
    function afterX() {
        var SomeVar = MyObject.MyProp1;
        alert(SomeVar);
    }
    x();
    afterX();
    

    Output:

    var a;a=JSON.parse(prompt(""));alert(a.a);
    

提交回复
热议问题