user5182503
user5182503

Reputation:

How to declare a collection with elements that extend some type in TypeScript?

I have a Set, and such code, that uses the 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

At LINE X I get error in generics. What is a correct way to declare the such Set?

Upvotes: 0

Views: 61

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250226

You just need to declare let mySet: Set<B>. Any type compatible with B will be valid, meaning any instance of B but also any derived classes (such as 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

When you retrieve instances from the set you will not know the actual type, you will need to test the type.

Upvotes: 2

Related Questions