Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 399
frenchie Avatar asked Mar 05 '12 03:03

frenchie


4 Answers

Try accessing the property in this way:

var SomeVar = MyObject['MyProp1'];
like image 162
lennel Avatar answered Nov 11 '22 15:11

lennel


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);
like image 30
Rob W Avatar answered Nov 11 '22 16:11

Rob W


To suppress this warning for a specific function, you can use the @suppress annotation:

/**
 * @suppress {missingProperties}
 */
function useJsonObject() { ... }

To turn off this warning globally, use the jscomp_off compiler flag to turn off the missingProperties class of warnings.

like image 7
bzlm Avatar answered Nov 11 '22 16:11

bzlm


Instead of putting the JSON content in the #TheJsonString object as HTML, you should put it in your page as actual javascript. If the server is generating the content in the page, then there's no reason that the server needs to generate HTML which you then parse. The server can just make a javascript variable inside a script tag and put the actual javascript data structure in it.

JSON.parse() is very useful for parsing ajax responses, but it really isn't needed when the server can just put the finished javascript right in the generated page in the first place.

like image 1
jfriend00 Avatar answered Nov 11 '22 15:11

jfriend00