How to access static members from instance methods in typescript?

You simply need ClassName.property :

class Logger {
  protected static PREFIX = '[info]';
  public log(message: string): void {
    alert(Logger.PREFIX + string); 
  }
}

class Warner extends Logger {
  protected static PREFIX = '[warn]';
}

MORE

from : https://basarat.gitbook.io/typescript/future-javascript/classes

TypeScript classes support static properties that are shared by all instances of the class. A natural place to put (and access) them is on the class itself and that is what TypeScript does:

class Something {
    static instances = 0;
    constructor() {
        Something.instances++;
    }
}

var s1 = new Something();
var s2 = new Something();
console.log(Someting.instances); // 2

UPDATE

If you want it to inherit from the particular instance’s constructor use this.constructor. Sadly you need to use some type assertion. I am using typeof Logger shown below:

class Logger {
  protected static PREFIX = '[info]';
  public log(message: string): void {
    var logger = <typeof Logger>this.constructor; 
    alert(logger.PREFIX + message); 
  }
}

class Warner extends Logger {
  protected static PREFIX = '[warn]';
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)