javascript - TypeScript 與正則表達式
TypeScript 說:
屬性 '
$1' 不存在於類型 '{ (pattern: string, flags?: string): RegExp; new(pattern: string, flags?: string): RegExp; }' 的值上
可以通過查看隨 TypeScript 0.8.2 附帶的 lib.d.ts 中的定義來解釋這種類型:
interface RegExp {
/**
* Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
* @param string The String object or string literal on which to perform the search.
*/
exec(string: string): RegExpExecArray;
/**
* Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
* @param string String on which to perform the search.
*/
test(string: string): bool;
/** Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal. */
source: string;
/** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */
global: bool;
/** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */
ignoreCase: bool;
/** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */
multiline: bool;
lastIndex: number;
}
declare var RegExp: {
new (pattern: string, flags?: string): RegExp;
(pattern: string, flags?: string): RegExp;
}
我的問題是我如何可以更改/更新這個,以便讓我能引用 RegExp.$1、RegExp.$2 等?最好是我可以單獨聲明的東西,因為我不打算直接編輯 lib.d.ts(它很可能會在更新時被替換)
我嘗試了這個但無濟於事:
declare var RegExp: {
new (pattern: string, flags?: string): RegExp;
(pattern: string, flags?: string): RegExp;
$1: any;
$2: any;
$3: any;
$4: any;
$5: any;
$6: any;
$7: any;
$8: any;
$9: any;
}
我想它們實際上應該用 string 類型來聲明。不過無論如何,這並不能消除錯誤。
除此之外,我也很好奇這到底意味著什麼(為什麼它既有用 new 宣告,又有不用 new 宣告的情況?)
new (pattern: string, flags?: string): RegExp;
(pattern: string, flags?: string): RegExp;
答案#1
你的 declare var 很接近。接口是開放的,所以你可以直接寫:
interface RegExp {
$1: string;
$2: string;
// etc
}
關於第二個,是因為 new RegExp('[A-Z]') 和 RegExp('[A-Z]') 都可以用來創建一個 RegExp(在類型上,它們既是可調用的函數也是構造函數)。
