【问题标题】:TypeScript annotate inherited members of derived classTypeScript 注释派生类的继承成员
【发布时间】:2018-02-24 04:07:53
【问题描述】:

假设我有一个基类和一些派生类。有没有办法注释继承的成员而不必在派生类中重新实现它们?

考虑这样的事情:

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);
  }
}

但是感觉不对劲,所以我很好奇是否可以注释继承的成员而不在所有派生类中重新实现它们中的每一个(唷)。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以为此使用泛型。

    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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多