繁体   English   中英

打字稿:基类的通用类型

[英]Typescript: Generic type in base class

我有以下代码作为简化示例:

class QueryArgs {
  studentId?: string;
  teacherId?: string;
}

class BaseValidator<T> {
  protected args: T;

  constructor(args: T) {
    this.args = args;
  }

  protected requireTeacher(): void {
    if (!this.args.teacherId) {
      throw new Error("teacherId required");
    }
  }
}

class QueryValidator extends BaseValidator<QueryArgs> {
  public validateAdmin(): QueryArgs {
    this.requireTeacher();
    return this.args;
  }
}

// Recreated implementation from a third party library
const args: QueryArgs = new QueryArgs();
args.studentId = "XXXX-XXX-XXX";

// Not the actual implementation just for illustration
const validator = new QueryValidator(args);
const validArgs = validator.validateAdmin();

我遇到的问题是requireTeacher方法中的BaseValidator类中this.args.teacherId具有错误Property 'teacherId' does not exist on type 'T'

我不确定Typescript的泛型部分中缺少什么。

理想情况下,TS在BaseValidator中知道argsQueryArgs的实例。

提前致谢!

您需要进一步将通用类型参数T约束为具有teacherId属性的类型。 现在,任何类型都可以作为T传递,这意味着您不能假定T具有teacherId

要约束类型,请尝试将class BaseValidator<T> class BaseValidator<T extends QueryArgs>更改为class BaseValidator<T> class BaseValidator<T extends QueryArgs> 这将T限制为扩展QueryArgs类型,以便确保T具有teacherId属性。

查阅本文,其中提到使用extends约束通用参数: https : //www.typescriptlang.org/docs/handbook/generics.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM