You can use the polymorphic this
type in the class for parent
and children
instead the Tree
class:
class Tree {
protected _parent?: this;
private children: Array<this> = [];
addChild(child: this) {
child._parent = this;
this.children.push(child);
}
get parent(): this | undefined {
return this._parent;
}
}
class MyClass extends Tree {
width: number = 10;
height: number = 10;
}
var mc1: MyClass = new MyClass();
var mc2: MyClass = new MyClass();
mc1.addChild(mc2);
console.log((mc2.parent as MyClass).height); // Works
console.log(mc2.parent?.height); // ok now
Playground Link
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…