Access to static properties via this.constructor in typescript
but in typescript this.constructor.prop causes error "TS2339: Property 'prop' does not exist on type 'Function'".
Typescript does not infer the type of constructor
to be anything beyond Function
(after all ... the constructor might be a sub class).
So use an assertion:
class SomeClass { static prop = 123; method() { (this.constructor as typeof SomeClass).prop; }}
Microsoft programmer talking this but there is not a good way to type constructor
. You can use this tip first.
class SomeClass { /** * @see https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146 */ ['constructor']: typeof SomeClass static prop = 123 method() { this.constructor.prop // number }}
Usually the simple way is:
class SomeClass { static prop = 123 method() { console.log(SomeClass.prop) //> 123 }}
Note that if you use this, subclasses of SomeClass
will access the SomeClass.prop
directly rather than SomeSubClass.prop
. Use basarat's method if you want subclasses to access their own static properties of the same name.