TypeScript static classes

后端 未结 12 700
太阳男子
太阳男子 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

    One possible way to achieve this is to have static instances of a class within another class. For example:

    class SystemParams
    {
      pageWidth:  number = 8270;
      pageHeight: number = 11690;  
    }
    
    class DocLevelParams
    {
      totalPages: number = 0;
    }
    
    class Wrapper
    { 
      static System: SystemParams = new SystemParams();
      static DocLevel: DocLevelParams = new DocLevelParams();
    }
    

    Then parameters can be accessed using Wrapper, without having to declare an instance of it. For example:

    Wrapper.System.pageWidth = 1234;
    Wrapper.DocLevel.totalPages = 10;
    

    So you get the benefits of the JavaScript type object (as described in the original question) but with the benefits of being able to add the TypeScript typing. Additionally, it avoids having to add 'static' in front of all the parameters in the class.

提交回复
热议问题