Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override static variables from inherited derived classes in typescript

Tags:

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'
like image 605
MonkeyBonkey Avatar asked Aug 17 '15 18:08

MonkeyBonkey


People also ask

Can static function be overridden in derived class?

Can we Override static methods in java? We can declare static methods with the same signature in the subclass, but it is not considered overriding as there won't be any run-time polymorphism. Hence the answer is 'No'.

How do you override a static variable?

No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods. The calling of method depends upon the type of object that calls the static method.

Are static attributes inherited?

Yes, Static members are also inherited to sub classes in java.

What is static property in typescript?

A static method uses the static keyword instead of the function keyword when we define it. Static members can be encapsulated with the public, private and protected modifiers. We call a static method directly on the class, using the class name and dot notation. We don't need to create an object instance.


2 Answers

I managed to get the static like this:

(<typeof SqlModel> this.constructor).tableName
like image 75
John T Avatar answered Oct 04 '22 22:10

John T


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"
like image 26
David Sherret Avatar answered Oct 04 '22 22:10

David Sherret