Normally we can use Class recursively in TypeScript in following ways:
class A {
b: B;
}
class B {
a: A;
}
But when we use it with decorator and metadata we will get a ReferenceError like this:
ReferenceError: Cannot access 'B' before initialization
Here is a simple reproduction code.
// test.ts
const decorator = (target: any, property: any) => {};
class A {
@decorator
b: B;
}
class B {
@decorator
a: A;
}
// tsconfig.json
{
"compilerOptions": {
"target": "es2017",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Is there a good way to use decorator mode with metadata in TS?
BTW, it won't appear when the target under ES6, but we cannot use super
in class constructor on those versions (refer: https://stackoverflow.com/a/51860850/7511849).
ps: I meet this problem when I use the NestJS framework recently, it uses decorator pattern and metadata a lot.