简体   繁体   English

Google Closure编译器中的动态类型发现

[英]Dynamic type discovery in Google Closure Compiler

I sometimes run into the situation that I have a JavaScript object of unknown type. 有时,我遇到一个类型未知的JavaScript对象的情况。 Then I perform a type check in script and call appropriate functions depending on the detected type. 然后,我在脚本中执行类型检查,并根据检测到的类型调用适当的函数。 eg like this 例如这样

/**
 * @param {!Array} aArray my array
 */
function actOnArray(aArray) {

}

/**
 * @param {*} aObject an arbitrary object
 */ 
function doSomething(aObject) {
  // make sure we have an array
  if ((null != aObject) && Array.isArray(aObject)) {
    actOnArray(aObject);
  }
}

Running this sniplet via advanced compilation in the google closure compiler yields the following warning message: 在Google Closure编译器中通过高级编译运行此代码段会产生以下警告消息:

JSC_TYPE_MISMATCH: actual parameter 1 of actOnArray does not match formal parameter
found   : *
required: Array at line 14 character 15
    actOnArray(aObject);

This warning makes sense, since the compiler does not know anything about the semantic of my type check. 该警告很有意义,因为编译器对我的类型检查的语义一无所知。

My question is: how can I annotate the code to tell the compiler that at a certain point I have gained information about a type. 我的问题是:如何注释代码以告知编译器在某一点上我已经获得了有关类型的信息。 In this example I would like to tell inside the if block that I now know for sure that the aObject parameter is of type !Array. 在此示例中,我想告诉if块,现在我肯定知道aObject参数的类型为!Array。

For some patterns, the compiler can automatically tighten the types within tests: 对于某些模式,编译器可以自动加强测试中的类型:

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @warning_level VERBOSE
// ==/ClosureCompiler==


/** @param {*} data */
function log(data) {
  if (data && data instanceof Array) {
    logArray(data);
  } else {
    console.log(data);
  }
}

/** @param {!Array} data */
function logArray(data) {
  for(var i = 0; i < data.length; i++) {
    log(data[i]);
  }
}

log([1, 2, 3]);

However, in many cases it cannot. 但是,在许多情况下却不能。 In those instances you need to type cast: 在这些情况下,您需要输入强制转换:

actOnArray(/** @type {!Array} */ (aObject));

note the extra parenthesis - they are required 请注意多余的括号-必须填写

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM