TypeScript 装饰器和循环依赖

JDR*_*JDR 4 javascript circular-dependency decorator undefined typescript

考虑使用装饰器的相互依赖代码示例(如下)。

现在考虑以下工作流程(是的,我确实想传递实际导出的类,因为我以后需要使用它们):

  1. 应用程序导入和运行 Parent.ts
  2. @Test(Child)导致应用程序Child.ts在装饰时导入
  3. 注意:Parent代码尚未到达该类
  4. 在Child.ts,@Test(Parent)装饰器被执行
  5. 此时,Parent未定义且无法传递给装饰器。

正如你所看到的,有一个讨厌的循环依赖,我看不到一种能够应用将类作为相互引用的参数的装饰器的方法。

请注意,我@Test以简洁为例。实际的装饰器是@HasManyand @BelongsTo- 所以我在这里有一个实际的用例。

我的问题是: “这个问题有解决方案吗?”

我担心没有,除非更改 TypeScript 的编译代码以推迟装饰过程,直到导入所有相关代码。

代码示例:

Decorators.ts:

    export function Test(passedClass: Function): Function {
        return function (model: Function): void {
            console.log(typeof passedClass);
        };
    }
Run Code Online (Sandbox Code Playgroud)

Parent.ts:

    import {Child} from "./Child";
    import {Test} from "./Decorators";

    @Test(Child)
    export class Parent {

    }
Run Code Online (Sandbox Code Playgroud)

Child.ts:

    import {Parent} from "./Parent";
    import {Test} from "./Decorators";

    @Test(Parent)
    export class Child {

    }
Run Code Online (Sandbox Code Playgroud)

Bru*_*ier 6

今天遇到同样的问题。我通过替换@Test(Parent)为@Test(() => Parent).

Parent我没有跟踪元数据中的类构造函数 ( ),而是跟踪返回构造函数 ( () => Parent)的 thunk 。这会延迟对Parent导入变量的评估,直到调用 thunk,这就是诀窍。