Reputation: 6489
Is there a way to specify a type for “any class which implements this abstract class”?
For example:
// LIBRARY CODE
abstract class Table {
static readonly tableName: string;
}
type TableConstructor = typeof Table;
// type TableConstructor = (new (...args: never) => Table);
const createORM = (tables: Array<TableConstructor>) => {
return {
executeQuery() {
// What type should the "tables" array be
// to support both of the next two lines
console.log(tables[0].tableName)
return new tables[0]();
// ~~~~~~~~~~~~~~~~
// Cannot create an instance of an abstract class
}
}
}
// EXAMPLE USER CODE
class Foo implements Table {
static get tableName() {
return 'foo';
}
}
const orm = createORM([Foo]);
TypeScript Playground Example Link
Upvotes: 1
Views: 66
Reputation: 6489
type TableConstructor = {
new (...args: never): Table
readonly tableName: string;
};
or even
type TableConstructor = (new (...args: never) => Table) & Omit<typeof Table, never>;
Here is the example with this implementation
Helpfully answered on the TypeScript discord: https://discord.com/channels/508357248330760243/968152049973874718/968163618401173564
Upvotes: 1