Imagine I have
abstract class Foo {
}
class Bar1 extends Foo {
constructor(someVar) { ... }
}
class Bar2 extends Foo {
constructor(someVar) { ... }
}
I want to create a static method that generates an instance of the final class (all constructors having the same signature). Here's what I would like:
abstract class Foo {
public static generateInstance(someVar) {
const self = new this(someVar);
}
}
However, because Foo
is abstract, this seems impossible. Is there any way around this?
UPDATE
What if these classes use their own templates?
abstract class Foo<M> {
}
class Bar1 extends Foo<SomeModel> {...}
Now, I want the generateInstance
method to be aware of the type SomeModel
. So, I attempted
public static generateInstance<A, T extends Foo<A>>(this: new (someVar: any) => T, someVar: any): T {
const self = new this(someVar);
return self;
}
Unless I explicitly call
Bar1.generateInstance<SomeModel>("blah")
, the returned result does not infer the data type. In other words, Bar1.generateInstance("blah")
doesn't recognize the data type.