Static variables and methods in Typescript

Typescript allows use of static variables and methods just like modern Javascript.

Static variables and methods are declared with a keyword static.

Static variables

Static variables exist within the class context, and are not carried forward to the object of the class.

Define a static variable like so -

class Human {
  static chaos: boolean = true;
}

The variable value is accessible using the class.

console.log(Human.chaos);
// true

.. but not against the object.

const joe = new Human();
console.log(joe.chaos);
// error TS2576: Property 'chaos' is a static member of type 'Human'

If you need a value in the object no matter the costs, you can always have the two variables with same names.

class Human {
  static chaos: boolean = true;
  chaos: boolean = true;
}

console.log(Human.chaos);
// true

const joe = new Human();
console.log(joe.chaos);
// true

Static methods / members

Static methods behave similar to static variables.

class Human {
  static chaos: boolean = true;
  chaos: boolean = true;

  static checkExists(): string {
    return "exists";
  }

  doubleCheckExists(): string {
    return "exists";
  }
}

console.log(Human.checkExists());
// exists

// console.log(Human.doubleCheckExists());
// error - cannot call a instance member

const joe = new Human();
console.log(joe.doubleCheckExists());
//exists

Note that static variables cannot be called by instance members and vice-versa.

Static variables / members are distinct from their instance counterparts at all times.

comments powered by Disqus