相关疑难解决方法(0)

使用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[].

typescript

7
推荐指数
1
解决办法
2111
查看次数

标签 统计

typescript ×1