0

I got 2 files which are importing each other

File A

import B from '...'

class A {
    
    ...

    public aOne(): number {
        return 1
    }

    public aTwo(): number {
        return B.bTwo() + 2
    }

    ...

 }

File B

import A from '...'

class B {
    
    ...

    public bOne(): number {
        return A.aOne() + 3 
    }

    public bTwo(): number {
        return 4
    }

    ...

 }

The issue is that I can't put one of the functions in a different place because they have to exist in their class but at the same time they are using each other and I get the circular dependency ERROR at build time. Is there a way to navigate around this without re-creating one of the functions in a different file? Thank you

3
  • You haven't stated why you want to avoid doing the refactoring and I sense that your example is a trivialised version of the actual problem you face. Commented Aug 18, 2022 at 8:08
  • I don't think there's a way around what you are asking - you have to break the cyclic dependency and that can only happen if the code is refactored in some way - likely by moving code that is used by both classes to another common service class that they can both import. Commented Aug 18, 2022 at 8:09
  • 1
    This should work, your functions are not static, that's why your compilation fails. Commented Aug 18, 2022 at 8:49

2 Answers 2

1

fixed version:

import { B } from './b';

export class A {    
    static aOne(): number {
        return 1
    }
    public aTwo(): number {
        return B.bTwo() + 2
    }
 }
import { A } from './a';

export class B {
    public bOne(): number {
        return A.aOne() + 3 
    }

    static bTwo(): number {
        return 4
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of importing it as import A from '...' use import type. It's going to be like the following:

import type A from '...'

and

import type B from '...'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.