TypeScript和RegExp

时间:2013-02-01 15:51:13

标签: javascript regex 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.$1RegExp.$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 (pattern: string, flags?: string): RegExp;
(pattern: string, flags?: string): RegExp;

1 个答案:

答案 0 :(得分:2)

您的declare var已关闭。接口是开放的,所以你可以写:

interface RegExp {
    $1: string;
    $2: string;
    // etc
}

关于第二个,这是因为new RegExp('[A-Z]')RegExp('[A-Z]')都可以创建一个RegExp(在类型术语中,它既是一个可调用函数又是一个构造函数)。