我想让静态方法的静态实现使用派生类的值.例如,在下面的简单示例中,当我调用时,User.findById()我希望它User在执行基类SqlModel中定义的实现时使用重写的tableName .
如何确保基类static 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我会得到一个错误,说明tablename没有定义,但如果我说SqlModel.tableName那么它不使用派生类表名
User.findById(1); //should call the knex query with the tablename 'User'
Run Code Online (Sandbox Code Playgroud)
你可以使用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"
Run Code Online (Sandbox Code Playgroud)
小智 7
I managed to get the static like this:
(<typeof SqlModel> this.constructor).tableName
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6436 次 |
| 最近记录: |