When to use Classes vs Modules in TypeScript?

后端 未结 2 898
名媛妹妹
名媛妹妹 2021-02-18 23:59

I\'m in the process of migrating a large codebase to Typescript, but wanted to get a good handle on when & where I should be using certain things.

Right now I have s

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 00:39

    • Consider using a module as a good option for a Singleton (one static object accessible everywhere) where a common usage is for libraries.
    • Consider using a class when you need to create several instances of this class or if you plan to extend this class.

    Basically modules are good for packing all your code into one convenient global object while class are smart to structure your code and data representation.

    [EDIT] The "internal modules" have been renamed "namespaces" moreover it is not discouraged to use namespaces when you can import modules. A namespace can be partial (i.e. described in many files) and while this is sometimes useful, this approach is too global to be optimised properly by the compiler. Read more here

提交回复
热议问题