Inheritance 从构造函数返回实例
有没有办法强制Typescript编译器从构造函数返回实例化实例?目前,由于无法找到这样做的方法,我无法将 在我发现编译器在子类化我的集合类型时输出以下内容之后Inheritance 从构造函数返回实例,inheritance,typescript,Inheritance,Typescript,有没有办法强制Typescript编译器从构造函数返回实例化实例?目前,由于无法找到这样做的方法,我无法将 在我发现编译器在子类化我的集合类型时输出以下内容之后 var MyCollection = (function (_super) { __extends(MyCollection, _super); function MyCollection() { _super.apply(this, arguments); } return MyColl
var MyCollection = (function (_super) {
__extends(MyCollection, _super);
function MyCollection() {
_super.apply(this, arguments);
}
return MyCollection;
})(Collection);
它不返回\u super.apply的结果(这是参数)
使得从集合类返回数组实例的整个技巧都不起作用
目前,我能想到的创建TypeScript编译器可以使用的东西的唯一方法是用JavaScript完成所有工作,然后围绕该类型定义一个接口 您需要执行类似于
集合
类的构造函数中的操作
将injectClassMethods
函数更改为可与其他类一起重用,或仅将现有类修改为如下所示:
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 );
}
现在您可以编写一个新的扩展类,如下所示:
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]);
}
}
…将导致typescript将myCollection
键入为Collection
而不是ExtendedCollection
,因为该函数的返回类型为Collection
这是一个悬而未决的问题
顺便说一下,我提出了要点,并使其更易于继承。此外,我还修复了其中的一些错误(例如
构造函数
和addAll
方法接受零个以上的参数而没有编译错误)。这种方法有点让人失望,因为ExtendedCollection
不再接受可变数量的参数,因为您无法应用asuper()
使用参数调用
。所以newextendedcollection(1,2,3)
只提供一个空数组。@oligofren哦,我没有注意到这一点,因为构造函数没有定义其他参数。我认为您只需要在子类的构造函数中手动完成它。我已经更新了我的答案。
var myCollection = new ExtendedCollection().add("Asdf");