TypeScript static classes

后端 未结 12 697
太阳男子
太阳男子 2020-12-04 13:34

I wanted to move to TypeScript from traditional JS because I like the C#-like syntax. My problem is that I can\'t find out how to declare static classes in TypeScript.

12条回答
  •  醉酒成梦
    2020-12-04 14:22

    This is one way:

    class SomeClass {
        private static myStaticVariable = "whatever";
        private static __static_ctor = (() => { /* do static constructor stuff :) */ })();
    }
    

    __static_ctor here is an immediately invoked function expression. Typescript will output code to call it at the end of the generated class.

    Update: For generic types in static constructors, which are no longer allowed to be referenced by static members, you will need an extra step now:

    class SomeClass {
        static myStaticVariable = "whatever";
        private ___static_ctor = (() => { var someClass:SomeClass ; /* do static constructor stuff :) */ })();
        private static __static_ctor = SomeClass.prototype.___static_ctor();
    }
    

    In any case, of course, you could just call the generic type static constructor after the class, such as:

    class SomeClass {
        static myStaticVariable = "whatever";
        private __static_ctor = (() => { var example: SomeClass; /* do static constructor stuff :) */ })();
    }
    SomeClass.prototype.__static_ctor();
    

    Just remember to NEVER use this in __static_ctor above (obviously).

提交回复
热议问题