typescript中的三阶嵌套类



编辑1,只是把它缩短了一点,与之前的代码相同

我只是想说,它看起来可能有很多代码,但都很空。


所以我想创建一个嵌套的类结构,看起来像这样:

let a = new A();
let b = new A.B();
let c = new A.B.C();
// etc

问题是typescript通过创建嵌套类的不同方法一直在与我斗争。一个看起来非常有前途和优雅的方法,我将称之为prototypetype方法来处理嵌套类。

type方法的问题是,它不能扩展到三阶嵌套类,也就是说,类C在类B中在类A中。

class A {
// error TS7022: 'B' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
public static B = class {
public static C = class { public constructor(name : string) { } }
// error TS2502: 'c' is referenced directly or indirectly in its own type annotation.
public c : A.B.C;
public constructor(c : A.B.C) { this.c = c; }
}
public b : A.B; public constructor(b : A.B) { this.b = b; }
}
namespace A {
export type B = InstanceType<typeof A.B>;
// error TS2456: Type alias 'C' circularly references itself.
export namespace B { export type C = InstanceType<typeof A.B.C>; }
}
export { A };

所以这不起作用,在过去的8个小时里,我一直在想为什么它不起作用。但我仍然不知道为什么。然后我找到了另一种方法(它更丑陋,但扩展后不会出现问题(,我将称之为namespace方法,如下所示:

class A { public b : A.B; public constructor(b : A.B) { this.b = b; } }
namespace A {
export class B { public c : A.B.C; public constructor(c : A.B.C) { this.c = c; } }
export namespace B { export class C { public constructor() { } } }
}
export { A };

关于我的实际问题,我完全可以使用namespace方法,为什么type方法会给我这些错误?它们看起来很奇怪,我不知道为什么在这种情况下,任何东西都是循环引用。

smth喜欢这项工作吗?

class C {}
class B {
static C = C
}
class A {
static B = B
}

最新更新