首页 > 解决方案 > 从 Tree 类继承 Typescript(访问父元素的属性)

问题描述

我想从 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 上的沙

标签: typescriptinheritancecastingtreetypescript-generics

解决方案


您可以this在类中使用多态类型来parent代替childrenTree

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

游乐场链接


推荐阅读