Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript and RegExp

TypeScript says:

The property '$1' does not exist on value of type '{ (pattern: string, flags?: string): RegExp; new(pattern: string, flags?: string): RegExp; }'

The type is explainable by looking at the definition from lib.d.ts that came with TypeScript 0.8.2:

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;
}

My question is how can I change/update this to allow me to reference RegExp.$1, RegExp.$2, etc.? Preferably something I can declare separately since I do not intend to directly edit lib.d.ts (which will most likely get replaced as it is updated)

I tried this to no avail:

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;    
}

I guess they should be declared with type string actually. But in any case it doesn't remove the errors.

In addition to this I'm also curious about what this means exactly (why is it declared with and without a new?):

new (pattern: string, flags?: string): RegExp;
(pattern: string, flags?: string): RegExp;
like image 294
Steven Lu Avatar asked Nov 04 '22 05:11

Steven Lu


1 Answers

Your declare var is close. Interfaces are open, so you can just write:

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

Regarding the second one, it's because new RegExp('[A-Z]') and RegExp('[A-Z]') both work to create a RegExp (in type terms, it's both an invokable function and a constructor function).

like image 186
Ryan Cavanaugh Avatar answered Nov 09 '22 02:11

Ryan Cavanaugh