blitzmann
blitzmann

Reputation: 7925

Generic class not respecting type

I have the following code:

class AugmentedSet<T>{
    private set: Set<T> = new Set<T>();

    add (item: any){
        this.set.add(item)
        item._parent = this;
    }
}

class Foo{}
class Bar{}

const foo = new Foo()
const bar = new Bar();
const augSet = new AugmentedSet<Foo>();
augSet.add(foo);
augSet.add(bar); // should not work, different type

I'm attempting to create a class that augments the Set class. For various reasons not shown in this example, I don't want to extend Set, nor do I want to modify the literal Set prototype. Instead, I simply want to create a Set-like object that is typed.

What I expect to happen is typescript allowing only Foo classes to be added via AugmentedSet.add(), however it seems to allow both Foo and Bar.

I am probably not understanding how to properly type this class / methods, so I'm looking for any guidance here. :)

Upvotes: 0

Views: 43

Answers (1)

Tamas Hegedus
Tamas Hegedus

Reputation: 29946

Foo and Bar are assignable to each other in your example because of structural typing, and they have the same set of properties. You can try it:

let foo: Foo = new Bar() ; // will typecheck

This is the reason your Set<Foo> accepts Bars too. Just add some differing methods to your Foo and Bar classes and will get the expected behavior.

Edit @Silvio in the comments noticed something I didn't, that's another, more direct reason. Must consider both to get the expected behavior.

Upvotes: 2

Related Questions