How to write a definition for circular reference in TypeScript

Asked 2 years ago, Updated 2 years ago, 110 views

If you define the following in Typescript:

class A {
  public b —A.B.
}

namespace A {
  classB{
  }
}

By classA definition

[ts] No exported member 'B' exists in namespace 'A'.

I get scolded, and if you reverse the definition order, classB.

[ts] Namespace declarations cannot precede classes or functions to merge with them.

I get scolded, is there a good solution?

typescript cyclic-reference

2022-09-30 21:34

1 Answers

Of course, B is export and there is no error.

class A {
    b: A.B.

    constructor(){
        This.b = new A.B()
    }
}

namespace A {
    export class B {
        n = 123
    }
}

I don't think I want to expose B to the outside, but I don't know what to do in that case.As a suggestion, let the private static variable retain the class B and use it to initialize it in the declaration section.

class A {
    private static B = class B {
        n = 123
    }
    b = new A.B()
}


2022-09-30 21:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.