I want to write es6 class:
class SomeClass {
static prop = 123
method() {
}
}
How to get access to static prop
from <
Accessing static properties through this.constructor
(as opposed to just doing SomeClass.prop
like normally you would) is only ever useful when you don't know the name of the class and have to use this
instead. typeof this
doesn't work, so here's my workaround:
class SomeClass {
static prop = 123;
method() {
const that = this;
type Type = {
constructor: Type;
prop: number; //only need to define the static props you're going to need
} & typeof that;
(this as Type).constructor.prop;
}
}
Or, when using it outside the class:
class SomeClass {
static prop = 123;
method() {
console.log(
getPropFromAnyClass(this)
);
}
}
function getPropFromAnyClass(target: T) {
type Type = {
constructor: Type;
prop: number; //only need to define the static props you're going to need
} & T;
return (target as Type).constructor.prop;
}