【问题标题】:How to declare a collection with elements that extend some type in TypeScript?如何在 TypeScript 中声明包含扩展某些类型的元素的集合?
【发布时间】:2018-10-24 04:08:21
【问题描述】:

我有一个Set,以及这样的代码,它使用Set

class A {

    public test1(): void {
        console.log("1");
    }
}

class B extends A {

    public test2(): void {
        console.log("2");
    }
}

class C extends B {

    public test3(): void {
        console.log("3");
    }
}

let mySet: Set<any extends B> = new HashSet();//LINE X

在第 X 行,我在泛型中遇到错误。声明此类 Set 的正确方法是什么?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你只需要声明let mySet: Set&lt;B&gt;。任何与B 兼容的类型都是有效的,这意味着B 的任何实例以及任何派生类(例如C)。

    class A {
    
        public test1(): void {
            console.log("1");
        }
    }
    
    class B extends A {
    
        public test2(): void {
            console.log("2");
        }
    }
    
    class C extends B {
    
        public test3(): void {
            console.log("3");
        }
    }
    
    let mySet: Set<B> = new Set<B>();//LINE X
    mySet.add(new B());
    mySet.add(new C());
    mySet.add(new A()); // error
    

    当您从集合中检索实例时,您将不知道实际类型,您需要测试类型。

    【讨论】:

    • 正如 Titan 所描述的,因为CB 的扩展,所以C 实例可以在任何需要B 的地方使用。就像关系 Pearson -> 老师:每个老师都是一个人,但不是每个人都是老师;)
    • TypeScript 中没有通配符泛型的等价物,请参阅stackoverflow.com/questions/33239227/…
    • @Pavel_K,原始问题中的示例不需要通配符。除非您可以细化问题,否则此答案就足够了。
    猜你喜欢
    • 2021-05-03
    • 2019-12-03
    • 2020-05-15
    • 2018-05-25
    • 1970-01-01
    • 2017-02-12
    • 2015-03-03
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多