如何在typescript中覆盖来自inehirted派生类的静态变量

Mon*_*key 9 typescript

我想让静态方法的静态实现使用派生类的值.例如,在下面的简单示例中,当我调用时,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)

Dav*_*ret 9

你可以使用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)

  • 我认为在打字稿> 1.8中不起作用。存在解决方法:(此this.constructor任意).tableName,如下所示:http://stackoverflow.com/questions/37727307/referencing-class-without-name-to-use-use-different-static-method-in-subclasses -在 (2认同)

小智 7

I managed to get the static like this:

(<typeof SqlModel> this.constructor).tableName
Run Code Online (Sandbox Code Playgroud)