call a public static method on an instance of a class in typescript

In TypeScript, we can call a public static method on an instance of a class by accessing the constructor function of the class and then calling the method using that constructor function. We cannot directly access a static method using an instance of a class.

Here's an example:

index.ts
class MyClass {
  public static myStaticMethod(): void {
    console.log("This is a static method");
  }

  public instanceMethod(): void {
    console.log("This is an instance method");
  }
}

const myInstance = new MyClass();

// Calling instance method on instance of MyClass
myInstance.instanceMethod(); // Output: "This is an instance method"

// Calling static method on instance of MyClass
MyClass.myStaticMethod(); // Output: "This is a static method"
460 chars
18 lines

In the above example, we create an instance of MyClass called myInstance. We can then call the instance method instanceMethod() directly on myInstance.

To call the static method myStaticMethod() on the instance myInstance, we use the constructor function MyClass to access the method.

Note that static methods are not bound to any instance of a class, while instance methods are.

gistlibby LogSnag