I want to write es6 class:
class SomeClass { static prop = 123 method() { } }
How to get access to static prop
from method()
without use SomeClass
explicitly? In es6 it can be done with this.constructor
, but in typescript this.constructor.prop
causes error "TS2339: Property 'prop' does not exist on type 'Function'".
You can't define a static property on an interface in TypeScript. Say you wanted to change the Date object, rather than trying to add to the definitions of Date , you could wrap it, or simply create your rich date class to do the stuff that Date doesn't do.
Note: The class or constructor cannot be static in TypeScript.
TypeScript allows us to encapsulate our static methods with access modifiers, just like regular methods.
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; } }
More on assertions
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With