Thomas Andersen Thomas Andersen - 1 month ago 31
TypeScript Question

TypeScript: Global static variable best practice

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

Answer

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