'Typescript Class as parameter that extends another class
I'm fairly new to Typescript and generics; I must be missing something hopefully trivial.
I'm trying to pass a (generic) class as an argument for a function, but this class extends from another specific class
An oversimplified example would be the following: lets say I have
class A {
static generate3() { return [new A(),new A(),new A()]; }
}
class B extends A {}
class C extends A {}
I want a method that I would call with any of the classes that inherite from A as parameters and return the result of that static method. Something like
f(B) // returns type B[]
I figured I can do
function f(type: typeof B){
return type.generate3();
}
But this requires me to define the class in advance. I also cannot use typeof B|typeof C cause in real life there is too many clases for this to be practical I tried
function f2<T>(type: typeof T extends A){
return type.hello();
}
where T is supposed to be the class, but it throws the following error: 'T' only refers to a type, but is being used as a value here.
I figured this works
function f3(type: typeof A){
return type.generate3();
}
But the return type of f3(B) is still A[] instead of the desired B[] I tried mixing the two like:
function f4<T extends A>(type: typeof A) : T[]{
return type.generate3() as T[]; // cast it
}
But the return type of f4(B) is still A[]
I don't understand it. Can anyone figure out what I'm I doing wrong?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
