MonkeyBonkey MonkeyBonkey - 1 month ago 16
TypeScript Question

How to override static variables from inehirted derived classes in typescript

I'd like to have the the static implementation of a static method use the derived class's value. For example, in the simple example below, when I call

User.findById()
I want it to use the overridden tableName
User
when executing the implementation defined in the base class SqlModel.

How do I make sure that the base classes static tableName uses 'User' and is this the right way of essentially declaring an abstract static property?

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;
}
}


And I would get an error saying tablename is not defined, but if I say SqlModel.tableName then it doesn't use the derived classes table name

User.findById(1); //should call the knex query with the tablename 'User'

Answer

You can use 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"
Comments