typescript - 从 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 上的沙箱
解决方案
您可以this
在类中使用多态类型来parent
代替children
类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
推荐阅读
- java - 使用 POI 仅编辑大 (>30 MB) Excel 文件中的工作表
- c - 在以另一种模式打开文件之前,我是否必须关闭文件?
- swift - 在 SwiftUI 的状态栏下查看
- ruby-on-rails - 活动存储附件“signed_id 委托给附件,但附件为零”但附件存在
- python - 使用 **kwargs 创建类属性
- scala - 如何为类型选项创建读取或格式[A]
- azure-pipelines - Azure Pipelines - 如何从成功生成工件的最新管道下载工件?
- c++ - 尽管程序重新启动,我如何保留静态变量的数据值?
- node.js - 对大文档的较慢的 mongodb 查询
- c - 给定一个排序的链表和要插入的值,编写一个函数以排序的方式插入该值