Typescript inheritance from the Tree class (access to properties of parent element)

Viewed 91

I want to make a convenient and beautiful (strongly typed) inheritance from the Tree class so that I don't have to cast the "parent" property of Tree to the desired type using the "as" service word

class Tree{
    protected _parent?:Tree;
    private children:Array<Tree> = [];
    addChild(child: Tree){
        child._parent=this;
        this.children.push(child);
    }
    get parent():Tree|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); // Error:  Property 'height' does not exist on type 'Tree'

sandbox on typescriptland.org

1 Answers

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

Related