3

例如,我想为类型添加一个静态quote方法RegExp

RegExp.quote = (text: String) => { ... };

但是当我尝试这样做时,我收到以下错误:

'{ $1: string; 类型的值不存在属性 'quote' $2:字符串;$3:字符串;$4:字符串;$5:字符串;$6:字符串;$7:字符串;$8:字符串;$9:字符串;最后匹配:字符串;(模式:字符串,标志?:字符串):正则表达式;新(模式:字符串,标志?:字符串):正则表达式;}'。

4

3 回答 3

2

恐怕只有这个丑陋的解决方案:

// add it 
RegExp['quote'] = (whatev:any):any => { return whatev;};

// Use it 
RegExp['quote']('asdf');

// The default behaviour is intact: 
var foo = new RegExp('/asdf/');

我认为模块会允许它工作,但我已经验证它不会。

请参阅:https ://stackoverflow.com/a/16824687/390330 和功能要求: https ://typescript.codeplex.com/workitem/917

于 2013-08-25T09:25:23.653 回答
1

请参阅Codeplex 上的问题- 如果问题被接受,您可以扩展接口。同时,您可以手动进行更改以创建您自己的自定义 lib.d.ts。

interface RegExpStatic {
    quote(text: string) : string;
}

您现在可以添加和访问该属性,因为类型系统知道它。

于 2013-08-25T16:56:34.363 回答
0

更新请参阅我的其他答案。我认为以下内容会起作用,但事实并非如此

您可以使用模块扩展 RegExp:

module RegExp{
    export function quote(whatev){return whatev;}
}

RegExp.quote('foo');

基本上使用模块将静态属性添加到现有实例。

于 2013-08-25T08:55:54.340 回答