Home > Software design >  How can I get around Circular Dependency in Typescript?
How can I get around Circular Dependency in Typescript?

Time:08-19

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

CodePudding user response:

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
    }
 }

CodePudding user response:

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 '...'
  • Related