4

I have this two parts of code which do the same thing.

But for you what is the best ? Using namespace or static class ?

    namespace MyMath {  
      const PI: number = 3.14;

      export function calculateCircumference(diameter: number): number {
        return diameter * PI;     
      }
      export function calculateRectangle(width: number, length: number): number {
        return width * length;     
      } 
    }

or

    class MyMathClass {  
      PI: number = 3.14;

      static calculateCircumference(diameter: number): number {  
        return diameter * PI;     
      }

      static calculateRectangle(width: number, length: number): number {
        return width * length;     
      } 
    }

Let me know what the best at your eyes ! Thank's

skfd
  • 2,528
  • 1
  • 19
  • 29
Nicolas B
  • 315
  • 3
  • 10
  • 1
    Possible duplicate of [Difference between classes and namespaces in typescript](https://stackoverflow.com/questions/48252136/difference-between-classes-and-namespaces-in-typescript) – Nicolas Gehlert Feb 07 '18 at 10:02

1 Answers1

7

well, as you can read here Difference between classes and namespaces in typescript they are fairly similar in what they can achieve.

For me personally I mostly use classes. Even if they only contain static methods, which is kind of rare. You have the freedom to add new logic and now it maybe makes sense to have an instance of said class.

Namespaces in my opinion are just for grouping stuff. So grouping multiple classes, interfaces, etc. in one namespace. Especially important if you plan that other dev use your stuff. Then namespaces are really handy for them, to differentiate between own code and imported code.

Nicolas Gehlert
  • 2,626
  • 18
  • 39