Reputation: 22963
Is there a way of coercing the Typescript compiler to return the instantiated instance from a constructor function? At the moment, the lack of being able to find a way of doing so is keeping my from subclassing a Collection type in Typescript.
After inspecting the output from the TypeScript compiler I have found that the compiler outputs the following when subclassing my Collection type
var MyCollection = (function (_super) {
__extends(MyCollection, _super);
function MyCollection() {
_super.apply(this, arguments);
}
return MyCollection;
})(Collection);
The fact that it does not return the result of _super.apply(this, arguments);
makes the whole trick of returning an array instance from the Collection class not work.
At the present point, the only way I can come up with of creating something working the TypeScript compiler will work with is to do everything in JavaScript and then define an interface around that type ...
Upvotes: 0
Views: 98
Reputation: 106770
You need to do something similar to what is in the Collection
class' constructor.
Change the injectClassMethods
function to be reusable with other classes or just modify the existing one to be like this:
static injectClassMethods(collection, prototype) {
// Loop over all the prototype methods and add them
// to the new collection.
for (var method in prototype) {
// Make sure this is a local method.
if (prototype.hasOwnProperty(method)) {
// Add the method to the collection.
collection[ method ] = prototype[ method ];
}
}
// Return the updated collection.
return( collection );
}
Now you can write a new extended class like so:
class ExtendedCollection extends Collection {
constructor(...items: any[]) {
var s = <any>super();
Collection.injectClassMethods(s, ExtendedCollection.prototype);
Array.prototype.push.apply(s, items);
return s;
}
// Example method
printFirstItem() {
document.write(this[0]);
}
}
Just be aware that with the current implementation doing something like...
var myCollection = new ExtendedCollection().add("Asdf");
...will cause myCollection
to be typed by typescript as a Collection
instead of an ExtendedCollection
because the return type of that function is Collection
.
There's an open issue about that here.
By the way, I forked that gist and made a few changes that will make it easier for inheriting. Also, I fixed some bugs in it (like the constructor
and addAll
methods accepting more than zero arguments without a compile error).
Upvotes: 1