如何防止警告'属性MyProp1从未在MyObject上定义'?

fre*_*hie 13 javascript google-closure google-closure-compiler

我有一些包含JSON字符串的HTML.在on DOM ready回调中,我有这样的事情:

MyObject = JSON.parse($('#TheJsonString').html());
Run Code Online (Sandbox Code Playgroud)

后来在我的代码中,我写了一些东西:

var SomeVar = MyObject.MyProp1;
Run Code Online (Sandbox Code Playgroud)

然后,当我通过Google闭包编译器运行代码时,我收到警告

属性MyProp1从未在MyObject上定义.

如何编写代码以便它不会生成警告?

Rob*_*b W 15

删除警告的最简单方法是定义JSON的结构.这可以使用@type标签完成:

/** @type {{MyProp1:string}} */
Run Code Online (Sandbox Code Playgroud)

MyProp1属性的名称在哪里,string是类型.

谷歌的Closure编译器将重命名该变量.如果你不想这样,你必须使用引号+括号而不是点符号:

MyObject['MyProp1']
Run Code Online (Sandbox Code Playgroud)

示例:将以下内容粘贴到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();
Run Code Online (Sandbox Code Playgroud)

输出:

var a;a=JSON.parse(prompt(""));alert(a.a);
Run Code Online (Sandbox Code Playgroud)


bzl*_*zlm 7

要禁止特定功能的此警告,您可以使用@suppress注释:

/**
 * @suppress {missingProperties}
 */
function useJsonObject() { ... }
Run Code Online (Sandbox Code Playgroud)

全局关闭此警告,请使用jscomp_off编译器标志关闭missingProperties 警告类.