Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : Namespace or static class

Tags:

typescript

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

like image 275
Nicolas B Avatar asked Oct 23 '25 16:10

Nicolas B


1 Answers

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.

like image 150
Nicolas Gehlert Avatar answered Oct 26 '25 07:10

Nicolas Gehlert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!