Typescript Static keyword to Property method and Constructor

In this blog post, We are going to learn Static keywords with properties, methods, and constructors of a class in typescript.

Static keyword in typescript

In TypeScript, static is a keyword applicable to both properties and methods within a class.

Static members can be accessed directly using the class names.

Example of TypeScript Static Properties and Methods

When you want to call any methods in a class, we will use an object instance for accessing its methods, Static methods will use class names.

In class,

  • Both static and non-static variables are declared.
  • Both static and non-static methods are declared.
  • Static methods and properties are accessed using class names.
  • Non-static methods and variables are accessed using instances of a class, i.e., objects.
class MyClass {
  static staticVariable: number = 0;
  nonStaticVariable: number = 0;
  constructor() {
    console.log("constructor");
  }
  nonStaticMethod() {
    console.log("non-static method");
  }
  static staticMethod() {
    console.log("Static method");
  }
}

MyClass.staticMethod(); // This works fine
let myClass1 = new MyClass();
myClass1.nonStaticMethod(); // This works fine

myClass1.staticMethod(); // Compilation Error
MyClass.nonStaticMethod(); // Compilation Error

It gives a compilation error for the below cases.

  • Attempting to call a static method with an object or instance name.

  • Attempting to call a non-static method with class names

Static Constructors in TypeScript

When the static keyword is applied to a constructor, the compiler throws a compilation error, stating Static modifier cannot appear on a construct declaration. In TypeScript, the static keyword does not apply to class constructors.

class ClassDemo {
  msg: string;
  static constructor(msg: string) {
    this.msg = message;
  }
  hello() {
    return "Hello, " + this.msg;
  }
}
let classDemo = new ClassDemo("world");

Example of TypeScript Static Member Variables and Methods

We can implement the static keyword in a different manner using static methods.

Declare a static initialization method responsible for initializing data.

class ClassDemo {
  static msg: string;
  constructor() {}
  static construct() {
    this.msg = "static TypeScript example";
    console.log("construct static method");
  }
}
console.log(ClassDemo.construct);