首页 > 解决方案 > 将 JSON 对象注释为 Google Closure Compiler 的数组

问题描述

我需要将 JSON 对象注释为数组,但我无法让它工作:

/** @type {Array} */
let resp = JSON.parse(response);

for (let item of resp) {

}

闭包编译器返回:

WARNING - initializing variable found   : * required: (Array|null)
        let resp = JSON.parse(response); 
               ^^^^^^^^^^^^^^^^^^^^

标签: google-closure-compiler

解决方案


因为 JSON 解析几乎可以返回任何内容,所以您必须对结果进行类型转换:

let resp = /** @type {Array} */ (JSON.parse(response));

注意额外的括号

您可以考虑在数组中添加项目的类型:

/** @type {Array<string>} */

推荐阅读