Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to static properties via this.constructor in typescript

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'".

like image 851
Artur Eshenbrener Avatar asked Oct 28 '15 09:10

Artur Eshenbrener


People also ask

How do you define a static property in TypeScript?

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.

Can static class have constructor TypeScript?

Note: The class or constructor cannot be static in TypeScript.

Does TypeScript have static methods?

TypeScript allows us to encapsulate our static methods with access modifiers, just like regular methods.


2 Answers

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

like image 89
basarat Avatar answered Sep 20 '22 02:09

basarat


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     } } 
like image 36
colder Avatar answered Sep 20 '22 02:09

colder