谷歌闭包编译器类型注释数组
Google Closure Compiler type annotations for array
在使用Google Closure Compiler时,我发现无法强制编译器对错误的变量类型发出警告。我使用了以下示例:
/** @typedef ({name: string, token: string}) */
var pendingItem;
/** @type (Array.<pendingItem>) */
var pending = [];
// NOTICE: the token is intentionally misspelled as "toke" to cause a warning
var dummyItem = {
name: 'NameHere',
toke: 'SomeToken'
};
// This should cause a warning, because of the
// type mismatch (toke instead of token)
pending.push(dummyItem);
// Do something useful so that the whole code wouldn't be optimized to 0 bytes
alert(pending.length);
它可以完美地编译,而不是给出预期的类型警告。但是如果你使用:
pending[1] = {
name: 'Second Name',
toke: 'Second Token'
}
得到预期的类型不匹配警告。
我理解这可能是因为push
没有定义类型检查,因为它是一个内置函数。可以预期,将pending
定义为pendingItem
的数组将强制这样做,但默认情况下不会这样做。
问题是是否以及如何可能向已经定义的函数(如push
)添加类型检查,以便在上面的示例中给出警告。我也明白,实现类似结果的一种方法是在dummyItem
之前添加/** @type {pendingItem} */
来强制类型,但出于教育目的,我想知道如何为push
这样的函数添加类型检查(或者可能更严格地定义pending
本身)。
还有谁能解释一下重命名对象属性背后的逻辑是什么?如果您编译上面的示例,它不会将dummyItem
的属性重命名为name
,但会将token
重命名为a
。
要强制对push
进行类型检查,必须在代码中使用正确的类型重新定义它。注意,使用对象文字表示法时,必须使用@type
而不是@param
来定义类型,因为我们将函数赋值给对象的形参,而不是定义普通函数。在这种情况下,它将是如下:
/** @type {function(pendingItem)} */
pending.push = function(item) {
Array.prototype.push.call(pending, item);
};
现在当尝试编译以下内容时:
// Still an intentionally misspelled "toke"
var dummyItem = {
name: 'NameHere',
toke: 'SomeToken'
};
// First warning
pending.push(dummyItem);
// Second warning
pending[1] = {
name: 'Second name',
toke: 'Second Token'
};
则两者都将生成类型不匹配警告,如预期的那样。
觉得将来可能对某个人有用。
相关文章:
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- 需要帮助设置json数组
- 不能从angular2中的子组件指定父组件中的数组
- 使用JS将数组转换为json对象
- 数组在递归方法中设置为null
- knockoutjs可观察数组
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 将数组从PHP传递到Javascript
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- 在函数中添加数组元素的数值
- 无法通过数组映射绑定
- javascript中的数组出错
- 在javascript中按注释记号对对象数组进行排序
- 在数组中使用注释字符构建复杂字符串
- 将 Javascript 点注释对象转换为基于数组的样式
- KnockoutJS中对象数组的正确注释是TypeScript
- 将不带分隔符的字符串中的所有字符拆分为带lotus注释的数组
- angular $inject属性和内联数组注释的区别
- 谷歌闭包编译器类型注释数组