在 Typescript 中从基类创建 Child 类的新实例

4 javascript oop inheritance typescript

我想从基类方法创建类的新实例。

这有点复杂,但我会尽力解释。

这是一个例子:

class Base(){
    constructor(){}

    clone(){
        //Here i want to create new instance
    }
}

class Child extends Base(){}


var bar = new Child();
var cloned = bar.clone();

clone instanceof Child //should be true!
Run Code Online (Sandbox Code Playgroud)

所以。从这个例子中我想克隆我的bar实例,那应该是实例Child

出色地。我正在尝试以下Bar.clone方法:

clone(){
    return new this.constructor()
}
Run Code Online (Sandbox Code Playgroud)

...这在编译代码中有效,但我有打字稿错误:

error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

我有什么想法可以处理这个问题吗?

谢谢。希望这对一些人有帮助1:)

Ger*_*ier 6

克隆未知对象时需要转换为通用对象。
最好的方法是使用该<any>语句。

class Base {
    constructor() {

    }

    public clone() {
        return new (<any>this.constructor);
    }
}

class Child extends Base {

    test:string;

    constructor() {
        this.test = 'test string';
        super();
    }
}


var bar = new Child();
var cloned = bar.clone();

console.log(cloned instanceof Child); // returns 'true'
console.log(cloned.test); // returns 'test string'
Run Code Online (Sandbox Code Playgroud)