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

时间:2021-07-05 08:35:12

标签: javascript typescript tuples variadic-tuple-types

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

我如何使它有效,正确的语法是什么?

游乐场: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?!! enter image description here

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

1 个答案:

答案 0 :(得分:1)

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 在其自身的初始化器中被直接或间接引用,因此需要显式类型注释