Adding a static method to TypeError

Topics: General
Oct 27, 2012 at 3:44 PM

Hi, we're trying to add a static method to the built-in JavaScript object TypeError.

Here is the code:

interface TypeError {
    myMethod (a, b): void;
}

TypeError.myMethod = function (a, b) {

 // Some work here
}

 

However, this errors out with:

"The property 'myMethod' does not exist on value of type '{ protoype: TypeError; (message?: string): TypeError; new(message?: string): TypeError; }'"

What are we doing wrong?

In general how do we add static methods to built-in types? 

Thanks

Noel

Coordinator
Oct 29, 2012 at 6:20 PM

Being unable to extend interfaces in lib.d.ts is a known issue (eg http://typescript.codeplex.com/workitem/176)  We're currently working on a fix.

Dec 19, 2013 at 4:28 AM
I've created a quick gist with my current workaround/solution for using Sugar.js's static extensions. I'm still pretty new to TypeScript, so I'm sure its not the best solution, but I did not see a workaround example in my own search so maybe this will help someone.
Coordinator
Dec 20, 2013 at 5:04 PM
Just to follow up - you should be able to extend interfaces in lib.d.ts. This was fixed in one of the early 0.9 versions, if I recall. You should be able to create additional interfaces with the names of those in lib.d.ts, and those interfaces will "merge". After that, you can add the new members to the existing objects.
Jan 6, 2014 at 3:50 PM
@jonturner, correct me if I'm wrong, but the thing that was fixed was the following:
interface TypeError {
    myMethod (): void;
}

TypeError.prototype.myMethod = function () {
}

var error = new TypeError();
error.myMethod(); // Okay
However, this does not address adding static methods to native objects, as in the TypeError example above.
TypeError.myMethod(); // Currently errors out but need this
There are a couple of these work items still open in the issue tracker.

https://typescript.codeplex.com/workitem/482
https://typescript.codeplex.com/workitem/1085