I think that is useful to access to static members :
Below an example:
class A {
protected static type: string;
public log(): string {
console.log(this.type);
}
}
class B extends A {
protected static type: string = 'C';
}
class C extends A {
protected static type: string = 'C';
}
b = new B();
b.log(); // => 'B'
c = new C();
c.log(); // => 'C'
We can't do it the way you suggest since this.type
is used to access an _instance_ property named type
, not a _static_ property.
However, your example works if you write it as follows:
class A {
"constructor": typeof A; // Explicitly declare constructor property
protected static type: string;
public log() {
console.log(this.constructor.type); // Access actual constructor object
}
}
class B extends A {
protected static type: string = 'B';
}
class C extends A {
protected static type: string = 'C';
}
let b = new B();
b.log(); // => 'B'
let c = new C();
c.log(); // => 'C'
By default the constructor
property of an instance is of type Function
, but you can specialize it in a class by manually declaring it. Once you do that you can access the statics through this.constructor.xxx
, and you'll get the properties of the constructor object that actually created the instance (i.e. the derived constructor object).
Most helpful comment
We can't do it the way you suggest since
this.type
is used to access an _instance_ property namedtype
, not a _static_ property.However, your example works if you write it as follows:
By default the
constructor
property of an instance is of typeFunction
, but you can specialize it in a class by manually declaring it. Once you do that you can access the statics throughthis.constructor.xxx
, and you'll get the properties of the constructor object that actually created the instance (i.e. the derived constructor object).