【问题标题】:Google Closure not failing on incorrect typeGoogle Closure 不会因错误类型而失败
【发布时间】:2020-04-18 14:53:30
【问题描述】:

我正在尝试为接收对象数组的函数编写注释。 我希望对象具有某些强制属性。

当我设置一个内部对象的类型并检查它时,它工作得很好。 但是一旦我添加了数组,编译器就会“跳过”测试对象类型检查。

这是一个示例代码 (run it)
(链接好像有问题,请复制粘贴下面的代码)

// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print
// ==/ClosureCompiler==

/**
* @record
* @struct
*/
const myType = function() {};
/** @type {!string} */
myType.prototype.arg1;

/**
* @param {myType} input
*/
function run_single(input) {
 console.log(input); 
}

/**
* @param {!Array<myType>} input_arr
*/
function run_array(input_arr) {
    console.log(input_arr);
};


var t = {"arg1": 1};
run_array([t]);
run_single(t);

我预计run_array 会失败。但事实并非如此。 但是,run_single 工作正常。

JSC_TYPE_MISMATCH: actual parameter 1 of run_single does not match formal parameter
found   : {arg1: number}
required: (myType|null) at line 26 character 11
run_single(t);

【问题讨论】:

    标签: javascript google-closure-compiler jsdoc


    【解决方案1】:

    不幸的是,闭包总是将数组字面量推断为 Array of ?。作为 ?将始终匹配,这会导致您看到的行为。

    你可以考虑使用 TypeScript,它在这里做得更好

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2020-05-27
      • 2012-08-09
      • 2023-03-17
      • 2022-11-29
      • 1970-01-01
      • 2021-07-10
      • 2014-11-06
      • 1970-01-01
      相关资源
      最近更新 更多