Sam
Sam

Reputation: 42357

How can I add a static method to an existing type?

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

Upvotes: 3

Views: 823

Answers (3)

Fenton
Fenton

Reputation: 250882

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.

Upvotes: 1

basarat
basarat

Reputation: 276299

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.

Upvotes: 0

basarat
basarat

Reputation: 276299

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

Upvotes: 3

Related Questions