TypeScript 和 RegExp

2024-03-13

打字稿 说:

该物业'$1'类型值不存在'{ (pattern: string, flags?: string): RegExp; new(pattern: string, flags?: string): RegExp; }'

该类型可以通过查看定义来解释lib.d.ts附带的打字稿 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;
}

我的问题是如何更改/更新它以允许我参考RegExp.$1, RegExp.$2, ETC。?最好是我可以单独声明的东西,因为我不打算直接编辑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;

Your declare var很接近。接口是开放的,所以你可以这样写:

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

至于第二个,是因为new RegExp('[A-Z]') and RegExp('[A-Z]')两者都用于创建 RegExp(就类型而言,它既是可调用函数又是构造函数)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript 和 RegExp 的相关文章

随机推荐