TypeScript: Access static methods within classes (the same or another ones)

Solution 1:

There is some code below, but there are some important concepts to bear in mind.

A static method does not exist on any instance. There are good reasons for this:

  1. It can be called before you have created a new instance
  2. It can be called from outside an instance, so you wouldn't know which instance the call was related to

So in all cases where you call the static method, you need to use the full name:

Test.aStaticFunction();

If the static method needs to call an instance method, you need to pass that in. This does set off alarm bells for me though. If the static method depends on an instance method, it probably shouldn't be a static method.

To see what I mean, think about this problem.

If I call Test.aStaticFunction() from outside of an instance, when 100 instances have been created, which instance should the static function use? There is no way of telling. If your method needs to know data from the instance or call methods on the instance, it almost certainly shouldn't be static.

So although the code below works, it probably isn't really what you require - what you probably need is to remove the static keyword and make sure you have an instance to call in your other classes.

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());
    }
}

Solution 2:

this is related to an instance whereas static members are independent of any instance. So if you want to access members of an instance within a static member you have to pass it in. However in that case I don't see a reason for having a static member in the first place. I believe you need two functions. one static and one non-static. That do two different things, so :

class Test {

    public  notaStaticFunction():void {
           this.aMemberFunction(); // <- Issue #1.
    }

    public static aStaticFunction():void {

    }

    private aMemberFunction():void {
          this.notaStaticFunction(); // <- Issue #2.
    }
}

class Another {
    private anotherMemberFunction():void {
          Test.aStaticFunction(); // <- Issue #3.
    }
}

That said you can share properties between static and member functions using static properties.