【发布时间】: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