Is it possible to create an array of classes in TypeScript? In vanilla JavaScript, this functionality is feasible:
class A {
constructor() {console.log('constructor');}
a() {}
}
const classesArray = [A];
new (classesArray[0])(); // Outputs 'constructor'
To ensure type safety for the array, an interface can be used. Here's an example of how this can be implemented in TypeScript:
interface Interface {
a();
}
class A implements Interface {
constructor() {console.log('constructor')}
a() {}
}
const typedArray: Interface[] = [A];
new (typedArray[0])();
Upon compiling, an error occurs:
Error:(16, 21) TS2322: Type 'typeof A' is not assignable to type 'Interface'.
Property 'a' is missing in type 'typeof A'.
This error indicates that
typeof A is not assignable to type 'Interface'
, implying that arrays cannot store classes as typeof
is utilized for instantiated objects.
The objective is to consolidate all classes into a single variable without instantiation and access them by index. Is there a way to achieve this in TypeScript?