i run situation have javascript object of unknown type. perform type check in script , call appropriate functions depending on detected type. e.g. this
/** * @param {!array} aarray array */ function actonarray(aarray) { } /** * @param {*} aobject arbitrary object */ function dosomething(aobject) { // make sure have array if ((null != aobject) && array.isarray(aobject)) { actonarray(aobject); } } running sniplet via advanced compilation in google closure compiler yields following warning message:
jsc_type_mismatch: actual parameter 1 of actonarray not match formal parameter found : * required: array @ line 14 character 15 actonarray(aobject); this warning makes sense, since compiler not know semantic of type check.
my question is: how can annotate code tell compiler @ point have gained information type. in example tell inside if block know sure aobject parameter of type !array.
for patterns, compiler can automatically tighten 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 = 0; < data.length; i++) { log(data[i]); } } log([1, 2, 3]); however, in many cases cannot. in instances need type cast:
actonarray(/** @type {!array} */ (aobject)); note parenthesis - required
Comments
Post a Comment