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

To call a protected static method on an instance of a class in TypeScript, you can use the Object.getPrototypeOf() method to access the prototype of the class, and then call the method on the prototype.

Consider the following example:

index.ts
class MyClass {
    protected static myMethod() {
        console.log("Hello from myMethod!");
    }

    public callMyMethod() {
        let proto = Object.getPrototypeOf(this);
        proto.constructor.myMethod();
    }
}

let myInstance = new MyClass();
myInstance.callMyMethod(); // Output: "Hello from myMethod!"
319 chars
14 lines

In the code above, we have a class MyClass with a protected static method myMethod(). To call this method on an instance of the class, we define a public method callMyMethod() that retrieves the prototype of the instance using Object.getPrototypeOf(), and then accesses the myMethod() method on the resulting constructor property. Finally, we create an instance of MyClass and call the callMyMethod() on it to invoke the myMethod() method.

Note that if the myMethod() method was not marked as protected, it could be called directly using MyClass.myMethod() without the need for the Object.getPrototypeOf() method.

gistlibby LogSnag