I would like to create two classes, Parent
and Child
, which each contain a reference to an instance of the other type. In many compiled languages, this is perfectly legal. For example, in C#, this compiles:
public class Parent {
public Child myChild;
public Parent() {
myChild = new Child();
myChild.myParent = this;
}
}
public class Child {
public Parent myParent;
}
However, in TypeScript I cannot get this to work. The best option I have found is to make one of the references of any
type, but this defeats any static type checking that Child
needs to do when working with Parent
or any of its other members.
class Parent {
myChild: Child;
constructor() {
this.myChild = new Child();
this.myChild.myParent = this;
}
}
class Child {
myParent: any;
}
In an ideal world, all object models would be easily describable by acyclic graphs, but the real world is messy and sometimes it is incredibly convenient to be able to navigate an object graph both ways.
Can I get two-way statically-typed object graph navigation like this in TypeScript? How?