Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Inheritance 从构造函数返回实例_Inheritance_Typescript - Fatal编程技术网

Inheritance 从构造函数返回实例

Inheritance 从构造函数返回实例,inheritance,typescript,Inheritance,Typescript,有没有办法强制Typescript编译器从构造函数返回实例化实例?目前,由于无法找到这样做的方法,我无法将 在我发现编译器在子类化我的集合类型时输出以下内容之后 var MyCollection = (function (_super) { __extends(MyCollection, _super); function MyCollection() { _super.apply(this, arguments); } return MyColl

有没有办法强制Typescript编译器从构造函数返回实例化实例?目前,由于无法找到这样做的方法,我无法将

在我发现编译器在子类化我的集合类型时输出以下内容之后

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
不再接受可变数量的参数,因为您无法
应用
a
super()
使用
参数调用
。所以
newextendedcollection(1,2,3)
只提供一个空数组。@oligofren哦,我没有注意到这一点,因为构造函数没有定义其他参数。我认为您只需要在子类的构造函数中手动完成它。我已经更新了我的答案。
var myCollection = new ExtendedCollection().add("Asdf");