When to use Classes vs Modules in TypeScript?

  • 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 now 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


It depends. A module should be a discrete set of "things" rather than just a jumbled collection of disparate classes, so if things seem like they belong together, use a module to group them.

I believe the TypeScript team is waiting to see how people use the language before they publish guidance, but I imagine people will publish a module where they currently publish a script - so jQuery would be a module, each jQuery Plugin would be a module, a testing framework would be a module, and an AOP framework would be a module - for example.

Tags:

Typescript