TypeScript使用自类类型克隆自实例

TypeScript使用自类类型克隆自实例,typescript,polymorphism,clone,Typescript,Polymorphism,Clone,我想克隆当前类实例,并在clone()内部创建多态类的实例,如下所示: class State { public clone():State { const state = new State(); this._copyData(state); return state; } protected _copyData(target:this):void { } } class StateExtend

我想克隆当前类实例,并在
clone()
内部创建多态类的实例,如下所示:

class State
{
    public clone():State
    {
        const state = new State();
        this._copyData(state);
        return state;
    }

    protected _copyData(target:this):void
    {
    }
}

class StateExtends extends State
{
    public clone():StateExtends
    {
        const state = new StateExtends();
        return state;
    }

    protected _copyData(target:this):void
    {
        super._copyData(target);
    }
}
class State
{
    public clone():this
    {
        const state = new this();
        this._copyData(state);
        return state;
    }

    protected _copyData(target:this):void
    {
    }
}

class StateExtends extends State
{
    protected _copyData(target:this):void
    {
        super._copyData(target);
    }
}
重写State类时,我希望
clone()
签名在所有类层次结构中保持不变。我可以这样做吗:

class State
{
    public clone():State
    {
        const state = new State();
        this._copyData(state);
        return state;
    }

    protected _copyData(target:this):void
    {
    }
}

class StateExtends extends State
{
    public clone():StateExtends
    {
        const state = new StateExtends();
        return state;
    }

    protected _copyData(target:this):void
    {
        super._copyData(target);
    }
}
class State
{
    public clone():this
    {
        const state = new this();
        this._copyData(state);
        return state;
    }

    protected _copyData(target:this):void
    {
    }
}

class StateExtends extends State
{
    protected _copyData(target:this):void
    {
        super._copyData(target);
    }
}
但这是行不通的


还有其他建议吗?

在运行时
只是类的一个实例,而不是类构造函数,因此您不能调用
newthis()
。但是您可以访问
this
constructor
属性,并调用
newthis.constructor()

有一点皱纹;不会编译,因为默认情况下,TypeScript将
构造函数
对象属性视为
函数
。这不是新的。这是有原因的

要获得
new this.constructor()
在没有警告的情况下编译,您需要像
new(this.constructor as any)(
)这样断言类型,或者使用正确的签名将
构造函数
属性添加到
状态

class State
{
    "constructor": new() => this; // no-arg polymorphic constructor

    public clone():this
    {
        const state = new this.constructor(); // okay
        this._copyData(state);
        return state;
    }

    // etc
}
希望这对你有用。祝你好运

谢谢。
“构造函数”:new()=>这个是不需要的。它不需要它就可以编译。TypeScript v2.6.2