什么是match()函数输入的TypeScript"类型"

use*_*723 1 javascript regex string types typescript

Javascript字符串匹配功能

从上面的文档中我看到String.prototype.match()函数的输入是"regexp".这显然不是一个字符串.它的类型是什么?

在TypeScript中如何声明输入变量?

regex:regexp = ^\d{2}\/\d{2}\/\d{4}$
Run Code Online (Sandbox Code Playgroud)

由于正则表达式不是可识别的类型,因此上述显然会引发错误.我该如何解决?

小智 6

您可以在以下位置查看类型信息lib.d.ts:

/**
  * Matches a string with a regular expression, and returns an array containing the results of that search.
  * @param regexp A variable name or string literal containing the regular expression pattern and flags.
  */
match(regexp: string): RegExpMatchArray;

/**
  * Matches a string with a regular expression, and returns an array containing the results of that search.
  * @param regexp A regular expression object that contains the regular expression pattern and applicable flags.
  */
match(regexp: RegExp): RegExpMatchArray;
Run Code Online (Sandbox Code Playgroud)

您可以看到正则表达式的类型是RegExp,并且有两个定义match,一个采用字符串,另一个采用RegExp.