I'm currently facing an issue with the code snippet below, which is a simplified example:
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;
}
}
// Sample implementation mimicking a third-party library
const args: QueryArgs = new QueryArgs();
args.studentId = "XXXX-XXX-XXX";
// Just for demonstration purposes, not actual implementation
const validator = new QueryValidator(args);
const validArgs = validator.validateAdmin();
The error I encounter lies within the BaseValidator
class and specifically in the requireTeacher
method where this.args.teacherId
triggers the message
Property 'teacherId' does not exist on type 'T'
.
I can't seem to figure out what I am overlooking in terms of TypeScript generics.
In an ideal scenario, TypeScript should recognize that in the BaseValidator
, the args
object is an instance of QueryArgs
.
Any help or insights would be greatly appreciated. Thank you!