1

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?

JamesFaix
  • 8,050
  • 9
  • 37
  • 73
  • Possible duplicate of [Circular Type References in TypeScript](http://stackoverflow.com/questions/24444436/circular-type-references-in-typescript) – JamesFaix Oct 04 '16 at 14:22
  • Works for me--what error are you getting? –  Oct 04 '16 at 16:47

2 Answers2

0

If both classes are in the same file (module) - you should have no problems. For example the following code works just fine:

class Parent
{
    public myChild: Child;

    public constructor()
    {
        this.myChild = new Child();
        this.myChild.myParent = this;
    }

    public callMe()
    {
        this.myChild.callMe();
    }

    public callMeAgain()
    {
        console.log("Parent");
    }
}

class Child
{
    public myParent: Parent;

    public callMe()
    {
        console.log("Child");
        this.myParent.callMeAgain();
    }
}

let p = new Parent();
p.callMe();

playground

UPDATE.

Unfortunately even with the latest typescript 2.0.3 crossreferencing between modules will not work in general case. A little bit more complicated cross referencing case (take this as an example) will still not work. For the reasons why you can refer to the previous link and this answer

Community
  • 1
  • 1
Amid
  • 21,508
  • 5
  • 57
  • 54
  • This solution technically works, but putting everything in one file is not a very scalable solution. – JamesFaix Oct 04 '16 at 15:29
  • I get that it works if they're in the same file, but why can't they be in different files? –  Oct 04 '16 at 17:33
0

This code builds correctly for me using TypeScript 2.0.2:

class Parent {
    myChild: Child;

    constructor() {
        this.myChild = new Child();
        this.myChild.myParent = this;
    }
}

class Child {
    myParent: Parent;
}
James Monger
  • 10,181
  • 7
  • 62
  • 98