Mark Pieszak Mark Pieszak - 10 months ago 60
TypeScript Question

When to use Classes vs Modules in TypeScript?

I'm in the process of turning a lot of code into Typescript, but wanted to get a good handle on when & where I should be using certain things.

Right now I have some large namespaces in modules:

(function (nameSpace) {

var privateVariables = '';

function privateFunctions () { }

// Public methods
nameSpace.someMethodHere = function () { };

}(window.nameSpace = window.nameSpace || {}));

My question is in TypeScript, is there any difference / benefit in me just turning these into just Classes? Or should it just be one large Module with classes (each method) inside of it?

module nameSpace {

export class someMethodHere {
// etc

// more classes (my methods) here ??


class nameSpace {

someMethodHere () {
// code
// more prototyped methods here

Or should I be setting them up in the same Module way I currently have? I was trying and it just kept giving me errors, not sure how I do
inside of a module without a class!

Answer Source

It depends. A module should be a discreet 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 are 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 a module, and AOP framework would be a module - for example.