3

For example, I want to add a static quote method to the RegExp type:

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

But when I try to do this, I receive the following error:

The property 'quote' does not exist on value of type '{ $1: string; $2: string; $3: string; $4: string; $5: string; $6: string; $7: string; $8: string; $9: string; lastMatch: string; (pattern: string, flags?: string): RegExp; new(pattern: string, flags?: string): RegExp; }'.

Sam
  • 40,644
  • 36
  • 176
  • 219

3 Answers3

3

I am afraid there is only this ugly solution:

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

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

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

I thought module would allow it to work but I have verified that it does not.

See : https://stackoverflow.com/a/16824687/390330 and a feature requets : https://typescript.codeplex.com/workitem/917

Community
  • 1
  • 1
basarat
  • 261,912
  • 58
  • 460
  • 511
1

See the issue on Codeplex - if the issue is accepted you could extend the interface. In the meantime, you could manually make that change to create your own custom lib.d.ts.

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

You can now add and access this property as the type system is aware of it.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • I think this only adds it to *instances* of `RegExp`. – Sam Aug 26 '13 at 09:57
  • Ah - yes, they haven't created a backing interface for the static element, they have declared it inline. I have opened an issue - you could temporarily make this change to your `lib.d.ts`: https://typescript.codeplex.com/workitem/1602 – Fenton Aug 27 '13 at 09:49
0

UPDATE see my other answer. I thought the following would work but it does not

You can extend RegExp using a module:

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

RegExp.quote('foo');

Basically use a module to add static properties to existing instances.

Community
  • 1
  • 1
basarat
  • 261,912
  • 58
  • 460
  • 511
  • I just tried this, but it seemed to overwrite the meaning of `RegExp` so I could no longer instantiate it. I also get a "Duplicate Identifier" error. – Sam Aug 25 '13 at 09:01
  • even if does work, it didn't for me beside interface String – Hassan Faghihi Jan 12 '16 at 07:08