我想让静态方法的静态实现使用派生类的值。例如,在下面的简单示例中,当我调用User.findById()
时,我希望它在执行基类SqlModel中定义的实现时使用覆盖的表名User
。
我如何确保基类静态tableName使用'User',这是本质上声明抽象静态属性的正确方式吗?
class SqlModel {
protected static tableName:string;
protected _id:number;
get id():number {
return this._id;
}
constructor(){
}
public static findById(id:number) {
return knex(tableName).where({id: id}).first();
}
}
export class User extends SqlModel {
static tableName = 'User';
name:string;
constructor(username){
this.name = username;
}
}
我会得到一个错误说表名没有定义,但如果我说SqlModel。tableName则不使用派生类表名
User.findById(1); //should call the knex query with the tablename 'User'
您可以使用this.tableName
:
class SqlModel {
protected static tableName: string;
public static outputTableName() {
console.log(this.tableName);
}
}
class User extends SqlModel {
protected static tableName = 'User';
}
User.outputTableName(); // outputs "User"
我设法得到这样的静态:
(<typeof SqlModel> this.constructor).tableName