打字稿:基本 class 中的通用类型
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();
我遇到的问题是 BaseValidator
class 中的 requireTeacher
方法 this.args.teacherId
有错误 Property 'teacherId' does not exist on type 'T'
.
我不确定我在 Typescript 的泛型部分遗漏了什么。
理想情况下 TS 会在 BaseValidator
中知道 args
是 QueryArgs
.
的一个实例
提前致谢!
您需要进一步将泛型类型参数 T
限制为具有 teacherId
属性 的类型。现在的方式是,任何类型都可以作为 T
传递,这意味着您不能假设 T
具有 teacherId
.
要限制类型,请尝试将 class BaseValidator<T>
更改为 class BaseValidator<T extends QueryArgs>
。这将 T
限制为扩展 QueryArgs
的类型,以便保证 T
具有 teacherId
属性.
查看这篇文章,其中提到使用 extends
约束泛型参数:https://www.typescriptlang.org/docs/handbook/generics.html
我有以下代码作为简化示例:
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();
我遇到的问题是 BaseValidator
class 中的 requireTeacher
方法 this.args.teacherId
有错误 Property 'teacherId' does not exist on type 'T'
.
我不确定我在 Typescript 的泛型部分遗漏了什么。
理想情况下 TS 会在 BaseValidator
中知道 args
是 QueryArgs
.
提前致谢!
您需要进一步将泛型类型参数 T
限制为具有 teacherId
属性 的类型。现在的方式是,任何类型都可以作为 T
传递,这意味着您不能假设 T
具有 teacherId
.
要限制类型,请尝试将 class BaseValidator<T>
更改为 class BaseValidator<T extends QueryArgs>
。这将 T
限制为扩展 QueryArgs
的类型,以便保证 T
具有 teacherId
属性.
查看这篇文章,其中提到使用 extends
约束泛型参数:https://www.typescriptlang.org/docs/handbook/generics.html