I seem to have encountered a dilemma where I am looking to have both the static
and abstract
keywords used for a member of an abstract class in TypeScript, but it appears that this combination is not supported.
The nearest workaround I could come up with is shown below:
abstract class A {
s: string;
n: number;
static identifier: string;
constructor(s: string, n: number) {
this.s = s;
this.n = n;
}
}
class B extends A {
static identifier: string = "B";
}
class C extends A {
static identifier: string = "C";
}
function identifyAndInstantiate(identifier: string, classes: (typeof A)[]) {
var identifiedClass = classes.find((classCandidateConstructor: typeof A) => { return identifier == classCandidateConstructor.identifier });
if (!identifiedClass) return;
//error here: Cannot create an instance of an abstract class.(2511)
var instance = new identifiedClass("foo", 12);
}
var classes: (typeof A)[] = [
B,
C
I've experimented with different collection types to solve this issue. The most successful approach I found was using a Map from the static member type to instances of the class, but it required manually mapping the values to their respective classes.
Another tactic I attempted was utilizing a Newable<T>
type that defines its constructor, but this resulted in losing access to the subclass' static properties (as did other methods that exposed the constructor).
Is there a way to access both a subclass' static properties and its constructor after retrieving it from a collection of classes?