TypeScript Static Unnamed Method with version 4.4<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

TypeScript Static Unnamed Method with version 4.4

Posted on: January 20, 2022

TypeScript version 4.4 gives the possibility to have a static block inside a class. The addition follows the EcmaScript standard to allow an unnamed function to be called when the static class is accessed for the first time. Like initializing a static variable in a class, the static block is called when the class is accessed first. The block is called right after the static variables. ß The following example shows that depending of static constants, the static variables are initialized by calling a function or not.

1function fetchGlobalCount(): number {
2 return 1;
3}
4class Constants {
5 static isDistributed = true;
6}
7class Telemetry {
8 static globalInstanceCount = 0;
9 static localIntanceCount = 0;
10
11 static {
12 if (Constants.isDistributed) {
13 Telemetry.globalInstanceCount = fetchGlobalCount();
14 Telemetry.localIntanceCount = Telemetry.globalInstanceCount + 1;
15 } else {
16 Telemetry.localIntanceCount = 0;
17 }
18 }
19 public static log(): void {
20 console.log(Telemetry.localIntanceCount);
21 }
22}
23
24Telemetry.log();

The main benefit is the initialization of static private variables. Before the unnamed static block, additional code would be needed to access the static class variable and set the value needed. However, for private variables, it would be problematic. Also, having the possibility to rely on try/catch block is possible inside the static block giving a clean, central place to initialize safely static values for your class.