This page looks best with JavaScript enabled

Static variables and methods in Typescript

 ·   ·  ☕ 2 min read

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 -

1
2
3
class Human {
  static chaos: boolean = true;
}

The variable value is accessible using the class.

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

.. but not against the object.

1
2
3
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things