打字稿注释派生类的继承成员



说我有一个基类和许多派生类。有没有办法注释继承的成员而无需在派生的类中重新实现它们?

考虑这样的东西:

class BaseModel {
  collection: Collection;
  constructor(collectionName: string) {
    this.collection = connectToCollection(collectionName);
  }
  create(data: {}) { // <- I would like to annotate 'data' in the derived classes
    this.collection.insert(data);
  }
}
class ModelA extends BaseModel {
  constructor(collectionName: string) {
    super(collectionName);
  }
}
class ModelB extends BaseModel {
  constructor(collectionName: string) {
    super(collectionName);
  }
}

create成员的参数对于ModelA和ModelB是不同的,因此我想单独注释它们。

我想我可以这样重新实现它们:

class ModelA extends BaseModel {
  constructor(collectionName: string) {
    super(collectionName);
  }
  create(data: ArgsForModelA) {
    this.super.create(data);
  }
}
class ModelB extends BaseModel {
  constructor(collectionName: string) {
    super(collectionName);
  }
  create(data: ArgsForModelB) {
    this.super.create(data);
  }
}

但这只是感觉不正确,所以我很好奇是否可以注释继承的成员而不重新实现每个派生类中的每个人(phew(。

您可以为此使用仿制药。

class BaseModel<T> {
  collection: Collection;
  constructor(collectionName: string) {
    this.collection = connectToCollection(collectionName);
  }
  create(data: T) {
    this.collection.insert(data);
  }
}
class ModelA extends BaseModel<ArgsForModelA> {
  constructor(collectionName: string) {
    super(collectionName);
  }
}
class ModelB extends BaseModel<ArgsForModelB> {
  constructor(collectionName: string) {
    super(collectionName);
  }
}

最新更新