使用TypeScript从基类中的静态方法实例化子类

Tri*_*tan 7 typescript

作为TypeScript的新手,在实例化子类类型的基类中实现静态工厂的最佳方法是什么.例如,考虑findAll基础模型类中的方法:

class BaseModel {
  static data: {}[];
  static findAll() {
    return this.data.map((x) => new this(x));
  }
  constructor(readonly attributes) {
  }
}

class Model extends BaseModel {
  static data = [{id: 1}, {id: 2}];
  constructor(attributes) {
    super(attributes);
  }
}

const a = Model.findAll();  // This is BaseModel[] not Model[]
Run Code Online (Sandbox Code Playgroud)

这返回BaseModel[]而不是Model[].

Tri*_*tan 8

为了回答我自己的问题,这在TypeScript中是一个众所周知的问题.Github问题Polymorphic这对静态方法有很长的讨论.解决方案如下:

export type StaticThis<T> = { new (): T };

export class Base {
    static create<T extends Base>(this: StaticThis<T>) {
        const that = new this();
        return that;
    }
    baseMethod() { }
}

export class Derived extends Base {
    derivedMethod() { }
}

// works
Base.create().baseMethod();
Derived.create().baseMethod();
// works too
Derived.create().derivedMethod();
// does not work (normal)
Base.create().derivedMethod();
Run Code Online (Sandbox Code Playgroud)

  • 我无法描述我花了多少时间来解决这个问题。多谢,伙计 (3认同)