Declare Static Members in TypeScript

In TypeScript, you can declare static members in classes. Static members are properties or methods that belong to the class itself rather than to instances of the class. In this lesson, we’ll go over how to declare static members in TypeScript with a code example.

Declaring Static Properties

To declare a static property in a class, you use the static keyword before the property name. Here’s an example:

class MyClass {
  static myStaticProperty = 123;

  constructor() {
    // constructor code here
  }
}

In this example, we declare a static property myStaticProperty with the value of 123. This property belongs to the MyClass class itself and not to any instances of the class.

To access a static property, you use the class name followed by the property name, like this:

console.log(MyClass.myStaticProperty); // 123

Declaring Static Methods

To declare a static method in a class, you also use the static keyword before the method name. Here’s an example:

class MyClass {
  static myStaticMethod() {
    console.log('Hello from my static method!');
  }

  constructor() {
    // constructor code here
  }
}

In this example, we declare a static method myStaticMethod that logs a message to the console. Like static properties, static methods belong to the class itself and not to any instances of the class.

To call a static method, you use the class name followed by the method name and parentheses, like this:

MyClass.myStaticMethod(); // logs "Hello from my static method!"

Conclusion

In conclusion, declaring static members in TypeScript can be a useful way to add properties and methods to a class that belong to the class itself rather than to any instances of the class. By using the static keyword, you can declare static properties and methods in your classes, and access them using the class name rather than an instance of the class.