Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Global static variable best practice

Tags:

typescript

I have this class where I need to increment a number each time the class is instantiated. I have found two ways to this where both ways works, but I am not sure yet on what is the best practice

  1. declare the variable in the module scope

    module M {   var count : number = 0;   export class C {     constructor() {       count++;     }   } } 
  2. declare the variable in the class scope and access it on Class

    module M {   export class C {     static count : number = 0;     constructor() {       C.count++;       }   } } 

My take is example two as it does not adds the count variable in the module scope.

See also: C# incrementing static variables upon instantiation

like image 859
Thomas Andersen Avatar asked May 09 '13 13:05

Thomas Andersen


People also ask

Should global variables be static?

A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.

Can we use static variable globally?

A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.

What is the difference between static global and normal global variables?

A global variable's scope is in all the files, while a static global variable's scope is just the file where it is declared.

How do I store a global variable in TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.


2 Answers

Definitely method 2 since that is the class that is using the variable. So it should contain it.

In case 1 you are using a variable that will become confusing once you have more than one classes in there e.g:

module M {    var count : number = 0;    export class C {     constructor() {       count++;     }   }    export class A{   } } 
like image 120
basarat Avatar answered Oct 04 '22 21:10

basarat


Both of them are okay, but method 2 more self explanatory, which means its less confusing when your code get more complex unless you are using the count to increase each time you instantiate a class from that module then method 1 is the way to go.

I prefer to do it this way:

module M {   export class C {     static count : number = 0;     constructor() {       C.count++;       }   } } 
like image 34
Mustafa Dwekat Avatar answered Oct 04 '22 20:10

Mustafa Dwekat