Access static methods from an instance in Typescript

Why can't I do this? Is this due to the technical limitations of Javascript / Typescript, or is it a Typescript developer design decision? The same code will work fine in Java or C #.

class Test {
  static str: string = "test";
  public static getTest(): string {
    return this.str;
  }
}

//works as expected
console.log(Test.getTest());
//won't compile
var test: Test = new Test();
console.log(test.getTest());
+4
source share
1 answer

but I would still like to know why.

Less magic. Static properties exist on instances Class. Its clear is that it is called from code instead of magically binding to a class or member function at runtime.

Is this due to technical limitations of Javascript / Typescript, or is it a design decision by Typescript developers

. . ES6, - : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

+3

Source: https://habr.com/ru/post/1617003/


All Articles