CodeTower
CodeTower

Reputation: 6333

Access static property in default nameless class in TypeScript

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

Upvotes: 5

Views: 2219

Answers (2)

user663031
user663031

Reputation:

You can use

this.constructor.someProperty

Upvotes: 2

Paarth
Paarth

Reputation: 10397

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)

Upvotes: 6

Related Questions