1

The code below has a circular dependency issue. A -> B -> A

Reproducible problem:

/a.ts

import {B} from './b';
import { Service } from './test';
@Service
export class A {
    static id = 'A'

    constructor(b: B) {
    }
}

/b.ts

import {A} from './a';
import { Service } from './test';
@Service
export class B {
    static id = 'B'
    constructor(a: A) {
    }
}

/test.ts

export function Service(target: any) {
// purposefully empty 
}

/index.ts

import 'reflect-metadata'
import {A} from './a'
import {B} from './b'

const paramTypesA = Reflect.getMetadata('design:paramtypes', A);
const paramTypesB = Reflect.getMetadata('design:paramtypes', B);


console.log('paramTypesA is', paramTypesA)
console.log('paramTypesB is', paramTypesB)

Expected output

paramTypesA is [ [Function: B] { id: 'B' } ]
paramTypesA is [ [Function: A] { id: 'A' } ]

Actual output

paramTypesA is [ [Function: B] { id: 'B' } ]
paramTypesB is [ undefined ]

Question: How to achieve the expected output

The goal is to detect circular dependency. But we also want to know what parameter exactly causes the circular dependency.

If reflect-metadata only output undefined, it is impossible to know which parameter provokes the circular dependency.

I already checked Detecting circular dependencies in TypeScript but this didn't help

TSR
  • 17,242
  • 27
  • 93
  • 197
  • what output will be if you change the order of imports? So swap import A and B. – Anton Sep 10 '20 at 10:18
  • I tried that already and the the actual output is `paramTypesA is [ undefined ] paramTypesB is [ [Function: A] { id: 'A' } ] ` . The expected output however should still be paramTypesA is `[ [Function: B] { id: 'B' } ] paramTypesA is [ [Function: A] { id: 'A' } ]` – TSR Sep 10 '20 at 10:19
  • In that case, it seems to me that TS is OK with that circular dependency. So, the problem is inside `reflect-metadata`. – Anton Sep 10 '20 at 10:21
  • Maybe this answer can help you, because you said "the goal is to detect circular dependency": https://stackoverflow.com/questions/37462055/detect-circular-dependencies-in-es6 – Anton Sep 10 '20 at 10:26

0 Answers0