How to define a "subclass of class" type?

1.6k views Asked by At
class SuperClass { ... }

class SubClass1 extends SuperClass { ... }
class SubClass2 extends SuperClass { ... }
class SubClass3 extends SuperClass { ... }

const foo: ??? = ...

For foo I'd like to give a type that means that foo is an instance of any class extending SuperClass. I know I could use union types and list all subclasses but there must be a better way. Somehow with extends or how to do it?


Update:

The reason I ask this is because I have this problem:

type SomeType = { foo: SuperClass };

public someMethod<T extends SuperClass>() {

  const bar: SomeType = ... ;

  const someSet: Set<T> = new Set();

  someSet.add(bar.foo);

Argument of type 'SuperClass' is not assignable to parameter of type 'T'. 'SuperClass' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'SuperClass'.

Hmm.. maybe I should just change Set<T> to Set<SuperClass>.

3

There are 3 answers

0
HTN On BEST ANSWER

What do you want to achieve? SuperClass should be fine for ???. If you want it to be union of EVERY subclasses of SuperClass: Well, it's not possible

0
HTN On

If you really want to have generic type, the closest answer I can come up is this:

interface SuperClass {
    a: string;
}

type SomeType<T extends SuperClass> = { foo: T };

function someMethod<T extends SuperClass>(bar: SomeType<T>) {
    const someSet: Set<T> = new Set();

    someSet.add(bar.foo);
}
0
Sergey Danyleuko On

This is one variant:

interface Interface {}

class SuperClass implements Interface{  }

class SubClass1 extends SuperClass {  }

const foo: Interface = new SubClass1();