【问题标题】:Typescript inheritance from the Tree class (access to properties of parent element)从 Tree 类继承 Typescript(访问父元素的属性)
【发布时间】:2021-04-28 22:47:32
【问题描述】:

我想从 Tree 类进行方便且美观的(强类型)继承,这样我就不必使用“as”服务字将 Tree 的“父”属性转换为所需的类型

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'

typescriptland.org 上的沙盒

【问题讨论】:

    标签: typescript inheritance casting tree typescript-generics


    【解决方案1】:

    您可以在parentchildren 的类中使用多态this 类型,而不是Tree 类:

    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

    【讨论】: