class 继承中的打字稿元组,丢失的类型

typescript tuple in class heritance, lost types

我如何用元组覆盖 class 数组并在索引中添加本机实例并保留类型?

我怎样才能让它有效,正确的语法是什么?

操场:playground

class Base {
    protected children?:Base[]
}
class Containers extends Base {
    protected override children:Array<Containers|Primitives>; 
}

class Primitives extends Base {
}

class A extends Containers {
 // so children should automaticly someting like : [A,A,B,...Containers|Primitives] ?
    protected override children:[A,A,B]
    init(){
        const i0 = this.children[0];
        const i1 = this.children[1]; 
        const i2 = this.children[2]; 
        const i3 = this.children[3]; // should Containers|Primitives|undefined because extends Containers ?
    }

}
class B extends Containers {

}

所以在这段代码中,A 可以在 children 索引中有本机实例,我在其中使用 getter 。 但是...其余 children 应该自动继承父级 Containers|Primitives 否?

这也很奇怪,如果我删除类型,一切都变成了实例 A ?!!

编辑:我知道我可以这样写! protected override children:[A,...Array<Containers|Primitives>] 但是我重复父 class 的代码,有没有避免重复的好方法?

class Base {
    protected children?: Base[]
}
class Containers extends Base {
    // let say, container entity can have childrens (Containers|Primitives)
    protected override children: Array<Containers | Primitives> = [];
}

class Primitives extends Base {
}

class A extends Containers {
    // Let say A have some native instance in children [A,A,B,...Containers|Primitives]
    protected override children: [A, A, B, ...Containers[] | Primitives[]] = [new A(), new A(), new B()];
    init() {
        const i0 = this.children[0];
        const i1 = this.children[1];
        const i2 = this.children[2];
        const i3 = this.children[3]; // // Primitives | Containers
    }

}
class B extends Containers {

}

您需要使用扩展语法

[A,A,B,...Containers|Primitives] 无法编译,因为您只能将 ... 用于数组

Playground

children在自己的初始化器中被直接或间接引用,所以需要显式的类型注解