javascripttypescriptclass

abstract static method in TypeScript


I'm looking for a way to implement an abstract static method in TypeScript.

Here an example:

abstract class A {
  abstract static b (): any // error
}

class B extends A {
  static b () {}
}

This is allowed with public, private and protected methods but not with a static method. TypeScript returns the following error:

'static' modifier cannot be used with 'abstract' modifier.ts(1243)

Is there any workaround?


Solution

  • Another way to handle this type of scenarios, could be to introduce a runtime check. The idea is to provide a default implementation that obviously won't work, and rely on runtime errors to throw error if the derived class hasn't overridden the method.

    abstract class A {
      static myStaticMethod(): any {
        throw new Error('Method not implemented! Use derived class');
      }
    }
    
    class B extends A {}
    
    B.myStaticMethod(); // error: Method not implemented...
    

    That can hint you to override the static method.

    class B extends A {
      static override myStaticMethod(): any {
        console.log('yay!');
      }
    }
    
    B.myStaticMethod(); // yay!