typescript 中,如何写一个单例类,因而作为一个父类,被其他需要单例模式的类继承?
发布于 3 年前 作者 daGaiGuanYu 2326 次浏览 来自 问答
class Singleton {
  private constructor(...args: any[]) {}
  static instance = new Singleton()
}

这种,不能被继承,可以将 constructor 改为 protected:

class Singleton {
  protected constructor(...args: any[]) {}

  private static instance: any // 问题在这里
  static getInstance() {
    return this.instance ||= new this()
  }
}

但,getInstance 的返回值是 any 类型
最后,我尝试了 Generic,但 instance 是个静态属性
感谢同仁指点

3 回复

private static instance: Singleton

@netwjx typescript 会认为子类通过 getInstance 获取到的实例是 Singleton 类型(虽然实际是子类类型)
这跟声明为 any 相比并没有优势
因为虽然声明成 any,但其实际类型也是子类类型

class Singleton {
  constructor(...args: any[]) {}

  private static instance: any;

  static getInstance<T extends typeof Singleton>(this: T): InstanceType<T> {
    return this.instance ||= new this()
  }
}

class Singleton1 extends Singleton {}

const s = Singleton1.getInstance()

Playground

回到顶部