用于闭包编译器的Regexp类型

Rao*_*ter 9 javascript regex types google-closure-compiler jsdoc

我目前正在为个人javascript模块添加类型注释,但是当我尝试键入函数时,我正在考虑将regexp作为参数,但以下尝试都没有工作:

/** @type {function(RegExp)} */
/** @type {function(regex)} */
Run Code Online (Sandbox Code Playgroud)

我只是得到:

WARNING - Bad type annotation. Unknown type regexp
Run Code Online (Sandbox Code Playgroud)

我应该在声明中使用什么类型?谢谢.

Chr*_*ert 11

RegExp对象在extern es3.js中Closure Compiler注释.这是一个接受对象的示例函数.RegExp

/**
 * @param {RegExp} regex A regular expression object.
 * @param {string} text Text to match.
 * @return {string} The first match in text.
 */
var firstMatch = function(regex, text) {
  var match = regex.exec(text);
  return match[1];
};

var text = 'Where art thou?';
var regex = new RegExp('^\\W*(\\w+)\\b', 'g');
var firstWord = firstMatch(regex, text);
alert(firstWord); // displays "Where"
Run Code Online (Sandbox Code Playgroud)

使用@type以下注释的相同功能:

/** @type {function(RegExp, string): string} */
var firstMatch = function(regex, text) {
  var match = regex.exec(text);
  return match[1];
};
Run Code Online (Sandbox Code Playgroud)

默认外部

Closure Compiler包含默认的externs,例如es3.js,es5.js和es6.js. 除非设置了以下标志,否则通常不需要显式指定这些外部文件:

闭包编译器应用程序:--use_only_custom_externs=true

Closure编译器服务UI:@exclude_default_externs true

Closure编译器服务API:exclude_default_externs=true

额外的外部人员

contrib/externs下还有其他外部功能,默认情况下不包含这些外部功能.可以使用--externs标志指定这些外部.