javascript - typescript 和正则表达式

标签 javascript regex typescript

typescript 说:

The property '$1' does not exist on value of type '{ (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;

最佳答案

您的声明 var 已关闭。接口(interface)是开放的,所以你可以写:

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

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

关于javascript - typescript 和正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14650014/

相关文章:

javascript - 为什么点击在触摸模式下不起作用

用于检查无线连接状态的Javascript

Javascript 正则表达式最多仅匹配 11 位数字、一个逗号和其后的 2 位数字

java - 如何使用 REGEX 匹配制表符和换行符而不匹配空格?

arrays - 如何键入 Typescript 数组以仅接受一组特定的值?

typescript - 如何在 TypeScript 中使用本地库开发项目?

javascript - Clipboard.writeText() 不适用于 Mozilla 和 IE

javascript - 如何在JS中编写正则表达式,前2个字符可以是数字或字母,后跟连字符,然后是6位数字?

javascript - 在 TypeScript 中包装 Firebase promise

javascript - jQuery DataTables 错误 - TypeError : Cannot read property 'fnInit' of undefined