In the pull request for adding polymorphic this, one use case given is a clone method. However, when I attempted an implementation of this, I hit the same problem as shelby3 noted in the comment chain:
how can polymorphic clone(): this be implemented if it is not legal to assign an instance of the subclass to this??? It seems instead the compiler will need to deduce that inheritance from Entity types clone() as an abstract method even though the base has an implementation, so as to insure that each subclass provides a unique implementation.".
Is there a solution to this, or do I just have to use casts to force typescript to compile such code, and hope that any sub classes don't forget to implement clone themselves?
See this example, without the <this> casts, the code would fail to compile. It also fails to detect that c.clone() has the wrong type:
interface Cloneable {
clone() : this
}
class ClassA implements Cloneable {
a: number = 0;
clone() : this {
let result = new ClassA();
result.a = this.a;
return <this>result;
}
}
class ClassB extends ClassA {
b: number = 0;
clone() : this {
let result = new ClassB();
result.a = this.a;
result.b = this.b;
return <this>result;
}
}
class ClassC extends ClassB {
c: number = 0;
// missing clone method
}
function test() {
const a = new ClassA();
const b = new ClassB();
const c = new ClassC();
const aClone = a.clone(); // aClone : ClassA
const bClone = b.clone(); // bClone : ClassB
const cClone = c.clone(); // typescript thinks cClone is ClassC, but is actually ClassB
alert(cClone.constructor.name); // outputs ClassB
}
test();
thisis much more useful to users of a class hierarchy than it is to implementers. I'm not sure there's a great way to get better type safety for implementers here...