In below example, How can i serve same purpose using Mixin while GenericClass is working expected.
import "reflect-metadata";
import Knex, { Knex as KnexSpace } from "knex";
export const knex = Knex({
client: "pg",
})
type Constructor<T = {}> = new (...args: any[]) => T;
const tableMetaName = Symbol("table");
export function Mixin<TBase extends Constructor>(Base: TBase) {
return class extends Base {
query = knex.table<KnexSpace.CompositeTableType<TBase>>(
Reflect.getMetadata(tableMetaName, Base).tableName
);
};
}
export class GenericClass<TBase extends {}> {
query = knex.table<KnexSpace.CompositeTableType<TBase>>(
Reflect.getMetadata(tableMetaName, this.constructor).tableName
);
}
class User {
id: number;
firstname?: string;
}
const userModal = Mixin(User);
new userModal().query.insert({ id: 1 }); // Error Argument of type '{ id: number; }' is not assignable to parameter of type 'typeof User | readonly (typeof User)[]'.
new GenericClass<User>().query.insert({ id: 1 });
sharing you same on typescript-playgroud
Aucun commentaire:
Enregistrer un commentaire