Take a look at this code snippet that involves inter-dependent code using decorators.
Let's walk through the workflow where the actual classes are passed for later use:
- The application imports and executes
Parent.ts
@Test(Child)
triggers the import ofChild.ts
while applying the decorator- Keep in mind: the class
Parent
has not been reached yet in the code - In
Child.ts
, the@Test(Parent)
decorator is invoked - At this stage,
Parent
is undefined and cannot be passed to the decorator
It's clear that there is a problematic circular dependency here, especially when trying to apply decorators that reference each other with classes as arguments.
Just to clarify, I used @Test
as a placeholder for the actual decorators @HasMany
and @BelongsTo
- these are real scenarios I'm dealing with.
Now, here's my question: "Is there a solution to this dilemma?"
I'm apprehensive that there may not be a straightforward solution unless TypeScript's compiled code is altered to delay the decoration process until all related code has been imported.
Check out this code snippet:
Decorators.ts
:
export function Test(passedClass: Function): Function {
return function (model: Function): void {
console.log(typeof passedClass);
};
}
Parent.ts
:
import {Child} from "./Child";
import {Test} from "./Decorators";
@Test(Child)
export class Parent {
}
Child.ts
:
import {Parent} from "./Parent";
import {Test} from "./Decorators";
@Test(Parent)
export class Child {
}