Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Classes vs Modules in TypeScript?

Tags:

typescript

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 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 ??
}

-OR-

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 nameSpace.someMethodHere inside of a module without a class!

like image 823
Mark Pieszak - Trilon.io Avatar asked Nov 06 '12 16:11

Mark Pieszak - Trilon.io


1 Answers

  • 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

like image 99
Flavien Volken Avatar answered Sep 21 '22 16:09

Flavien Volken