How to access static methods within classes with TypeScript?

Sometimes, we want to access static methods within classes with TypeScript.

In this article, we’ll look at how to access static methods within classes with TypeScript.

How to access static methods within classes with TypeScript?

To access static methods within classes with TypeScript, we access it as a property of the class.

For instance, we write

interface IHasMemberFunction {
  aMemberFunction(): void;
}

class Test {
  public static aStaticFunction(aClass: IHasMemberFunction): void {
    aClass.aMemberFunction();
  }

  private aMemberFunction(): void {
    Test.aStaticFunction(this);
  }
}

class Another {
  private anotherMemberFunction(): void {
    Test.aStaticFunction(new Test());
  }
}

to call the Test.aStaticFunction static method in the Another class’ anotherMemberFunction method and in the Test class’ aMemberFunction method.

We define the static method with the static keyword.

Conclusion

To access static methods within classes with TypeScript, we access it as a property of the class.