Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp type for closure compiler

I'm currently adding type annotation to a personnal javascript module, but I'm currently stuck when trying to type function taking a regexp as a parameter, but none of the follwing tries is working :

/** @type {function(RegExp)} */
/** @type {function(regex)} */

I'm only getting :

WARNING - Bad type annotation. Unknown type regexp

What type should I use in the declaration? thanks.

like image 427
Raoul Supercopter Avatar asked Jun 01 '12 15:06

Raoul Supercopter


1 Answers

The RegExp object is annotated for the Closure Compiler in the extern es3.js. Here is an example function that accepts a RegExp object.

/**
 * @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"

The same function annotated using @type:

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

Default Externs

The Closure Compiler includes default externs such as es3.js, es5.js, and es6.js. These externs files do not normally need to be explicitly specified, unless the following flag is set:

Closure Compiler Application: --use_only_custom_externs=true

Closure Compiler Service UI: @exclude_default_externs true

Closure Compiler Service API: exclude_default_externs=true

Additional Externs

There are additional externs available under contrib/externs that are not included by default. These externs may be specified with the --externs flag.

like image 71
Christopher Peisert Avatar answered Sep 19 '22 03:09

Christopher Peisert