【问题标题】:Typescript - Can I have mutually referencing classes?Typescript - 我可以有相互引用的类吗?
【发布时间】:2016-10-05 02:27:06
【问题描述】:

我想创建两个类,ParentChild,每个类都包含对另一种类型实例的引用。在许多编译语言中,这是完全合法的。例如,在 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


【解决方案1】:

此代码使用TypeScript 2.0.2 为我正确构建:

class Parent {
    myChild: Child;

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

class Child {
    myParent: Parent;
}

【讨论】:

  • 不,他们不需要。 OP 发表评论时忽略了另一个答案,因为它们在同一个文件中。
  • 那么,OP 的代码是否有问题,还是应该按原样工作?
  • OP 的代码没有问题 - 我已经更新了我的答案。
【解决方案2】:

如果两个类都在同一个文件(模块)中 - 你应该没有问题。例如下面的代码就可以正常工作:

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

更新。

不幸的是,即使使用最新的 typescript 2.0.3,模块之间的交叉引用在一般情况下也不起作用。稍微复杂一点的交叉引用案例(将其视为example)仍然不起作用。至于原因大家可以参考上一个链接和这个answer

【讨论】:

  • 此解决方案在技术上可行,但将所有内容放在一个文件中并不是一个非常可扩展的解决方案。
  • 我知道如果它们在同一个文件中它可以工作,但为什么它们不能在不同的文件中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 2015-11-05
  • 2011-03-19
相关资源
最近更新 更多