【发布时间】:2016-10-05 02:27:06
【问题描述】:
我想创建两个类,Parent 和Child,每个类都包含对另一种类型实例的引用。在许多编译语言中,这是完全合法的。例如,在 C# 中,它会编译:
public class Parent {
public Child myChild;
public Parent() {
myChild = new Child();
myChild.myParent = this;
}
}
public class Child {
public Parent myParent;
}
但是,在 TypeScript 中,我无法让它工作。我发现的最佳选择是创建any 类型的引用之一,但这会破坏Child 在使用Parent 或其任何其他成员时需要执行的任何静态类型检查。
class Parent {
myChild: Child;
constructor() {
this.myChild = new Child();
this.myChild.myParent = this;
}
}
class Child {
myParent: any;
}
在理想世界中,所有对象模型都可以很容易地用无环图来描述,但现实世界是混乱的,有时能够以两种方式导航对象图非常方便。
我可以在 TypeScript 中获得像这样的双向静态类型对象图导航吗?怎么样?
【问题讨论】:
-
为我工作——你遇到了什么错误?
标签: typescript