使用泛型来声明类方法的返回值类型

时间:2018-03-21 18:23:16

标签: typescript typescript2.0 tsc

我有以下内容:

$("#divLoading").hide();

我想要做的是声明这个包装器方法的返回类型......像这样:

export class RootCtrl {

  m: Model<any>;

  constructor(m: Model<any>) {
    this.m = m;
  }

  doFindMany(query: object, options?: CDTModelOpts, cb?: MongoErrorCB){

    const Model = this.m;

    // cb is optional, if cb == null, returns promise
    const {populate, lean} = options || ({} as CDTModelOpts);

    let q = Model.find(query);

    if (populate && populate.length > 0) {
      q = q.populate(populate);
    }

    if (lean !== false) {
      q = q.lean();
    }

    return q.lean().exec(cb)
  }

}

返回类型,是传入的Model值的类型。 我使用的语法完全是假的。有没有办法让返回类型将输入参数的类型反映到构造函数?

1 个答案:

答案 0 :(得分:1)

似乎你需要这样的东西。

  export class RootCtrl<ModelType> {

  m: Model<ModelType>;

  constructor(m: Model<ModelType>) {
    this.m = m;
  }

  doFindMany(query: object, options?: CDTModelOpts, cb?: MongoErrorCB): Array<Model<ModelType>>{

    const Model = this.m;

    // cb is optional, if cb == null, returns promise
    const {populate, lean} = options || ({} as CDTModelOpts);

    let q = Model.find(query);

    if (populate && populate.length > 0) {
      q = q.populate(populate);
    }

    if (lean !== false) {
      q = q.lean();
    }

    return q.lean().exec(cb)
  }

}