在打字稿中考虑这些类和模型。
class ApplicantModel {
name: string = '';
}
abstract class BaseApplicant {
abstract handleApplicantData<T>(applicantData: T, isPrimaryApplicant: boolean): void;
}
class Applicant extends BaseApplicant {
handleApplicantData<ApplicantModel>(applicantData: ApplicantModel): void {
// Error: This type parameter might need an `extends ApplicantModel` constraint.
this.processApplicant(applicantData);
}
processApplicant(applicant: ApplicantModel): void {
console.log(applicant.name);
}
}
我收到错误:
Argument of type 'ApplicantModel' is not assignable to parameter of type 'ApplicantModel'.(2345)
input.tsx(10, 23): This type parameter might need an `extends globalThis.ApplicantModel` constraint.
为什么我需要使用扩展约束。为什么“ApplicantModel”类型的参数不能分配给“ApplicantModel”类型的参数?
就您而言:
handleApplicantData<ApplicantModel>(applicantData: ApplicantModel): void {}
ApplicantModel
指的是泛型名称而不是类型,如你想做的是这样的:
handleApplicantData<T extends ApplicantModel>(applicantData: T): void {}
但是由于这也会引发错误,因此您必须在 BaseApplicant 类中执行此操作:
abstract handleApplicantData<T extends ApplicantModel>(
applicantData: T,
isPrimaryApplicant: boolean
): void;
或者如果您想保持灵活性:
abstract handleApplicantData(
applicantData: unknown,
isPrimaryApplicant: boolean
): void;
这仍然允许您在子类中将该函数声明为通用函数。