4

I want to clone the current class instance and create inside clone() an instance of a polymorphic class, something like this:

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);
    }
}

When overriding the State class I want the clone() signature to stay the same in all classes hierarchy. Can I do something like this:

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);
    }
}

But this is not working.

Any other suggestions?

1 Answer 1

5

At runtime this is just an instance of the class, not the class constructor, so you can't call new this(). But you can access the constructor property of this and call new this.constructor().

There's a little wrinkle; that won't compile since by default, TypeScript considers the constructor object property to be Function. Which isn't newable. There are reasons for this.

To get new this.constructor() to compile without warning, you either need to assert the type like new (this.constructor as any)(), or add a constructor property to State with the right signature:

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

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

    // etc
}

That should hopefully work for you. Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

thanks. the "constructor": new() => this; is not needed. it compile without it. TypeScript v2.6.2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.