5

If I define a class like this (in a file called. MyClass.ts)

export default class {
    static someProperty = 1;

    someMethod() {
       var a = ????.someProperty
    }

}

How do I access someProperty. Using this.someProperty does not work, obviously. Neither can a name be used. Had it been a named class it could be accessed through SomeClassName.someProperty.

If I load the module in another file. I can access it via:

MyClass.someProperty
CodeTower
  • 6,293
  • 5
  • 30
  • 54
  • If it's a static property that's how you'd access it internally as well... is it not working? – Heretic Monkey Sep 18 '16 at 21:19
  • Possible duplicate of [How to access static members from instance methods in typescript?](http://stackoverflow.com/questions/29244119/how-to-access-static-members-from-instance-methods-in-typescript) –  Sep 19 '16 at 03:20
  • @MikeMcCaughan Do you mean `this.someMethod`? Or just `someMethod`? Neither will work. –  Sep 19 '16 at 03:23
  • @MikeMcCaughan Yes you would use its name. Problem here is that the class does not have a name. – CodeTower Sep 19 '16 at 07:40

2 Answers2

6

You're using an anonymous class expression here. I could be wrong, but I believe naming the class expression is the only way you could access that variable.

 export default class ClassName {
    static someProperty = 1;

    someMethod() {
        return ClassName.someProperty;
    }

}

Your consumers can still name that class whatever they want (MyClass in your earlier example)

Paarth
  • 9,687
  • 4
  • 27
  • 36
2

You can use

this.constructor.someProperty
  • 1
    Using this gives a compiler error: "Property 'someProperty' does not exist on type 'Function'" – CodeTower Oct 26 '16 at 11:38
  • 1
    To use it this way unfortunately you need to cast type, like so: `const x = (this.constructor).someStaticProp` – Pavel Jan 31 '18 at 05:55