Search code examples
javascriptgoogle-closure-compilergoogle-closure

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


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

MyObject = JSON.parse($('#TheJsonString').html());

Later in my code, I write something this:

var SomeVar = MyObject.MyProp1;

And then when I run the code through the Google closure compiler, I get the warning

Property MyProp1 never defined on MyObject.

How should the code be written so that it doesn't generate a warning?


Solution

  • 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);