How to make the static member type of a class point to the type of the subclass

Viewed 33
class SingletonBaseClass {
  static singleton: SingletonBaseClass | null = null;

  static instance() {
    if (!this.singleton) {
      this.singleton = new this();
    }
    return this.singleton;
  }

  static destroy() {
    this.singleton = null;
  }
}

class Demo extends SingletonBaseClass {
  hello() { }
}

Demo.instance().hello();

Above is the code, Demo.instance() will be considered an instance of SingletonBaseClass instead of Demo, so Demo.instance().hello() will report a TypeScript error.

Is there any way to make the return type of Demo.instance() be SingletonBaseClass?

1 Answers

you could just cast it:

(Demo.instance() as Demo).hello();
Related