mizech mizech - 6 days ago 7
Javascript Question

TypeScript: What's the difference between a Module and a Class with Static members?

I'm learning TypeScript.

After having a look a modules ( https://www.typescriptlang.org/docs/handbook/modules.html ) I asked myself : "What's the difference between a class and a module?"

Both can be used to structure and encapsulate data / behavior within my code ...

Searched a bit and found this resource which explained the difference (partly) to me : https://msdn.microsoft.com/en-us/library/7825002w(v=vs.90).aspx

But thinking a bit further based upon what is explain in the article:

If I made a class with static properties and methods. That would be quite similar to what a module is? Or am I wrong there?

So therefore my question:

What's the difference between a module and a class with static members (like for example 'Math') ?

Answer

Modules allow you to structure and separate your code. Depending on the module type that might be file based (for the external/es6 modules) or namespace based (for the internal modules), spread across multiple files.

There are multiple reasons to use modules instead of classes, like packaging and loading. Also, you can't declare a class inside another class, so unless you can structure your code in such a way that one class is enough to encapsulate an entire feature they won't be able to replace a module.

Comments