This is my function that populates an object based on interface type:
public _fillAddModel<T>(lessonId: number, studyPeriodId: number, confirmed: boolean = false): T {
let data: T;
data = {
lesson: this.substitution.lessonNumber,
schoolStudyPeriod: GlobalModel.getSelectedPeriod().id,
confirmed: true
};
return data;
}
You can call it like this:
let data = this._fillAddModel<ISubstitutionModelTeacher>(1, 2, true);
let data = this._fillAddModel<ISubstitutionModelAddTeacherSubject>(1, 2, true);
In this function, I populate the object using the T
interface and then continue to fill additional fields after that:
data.subsDate = this.substitution.date;
All interfaces extend a main interface called ISubstitutionModelAdd
:
export interface ISubstitutionModelTeacher extends ISubstitutionModelAdd {
newTeacher: number;
subsDate: string;
}
export interface ISubstitutionModelAddTeacherSubject extends ISubstitutionModelAdd {
newTeacher: number;
subsDate: string;
classSubject: number;
}
export interface ISubstitutionModelAddFree extends ISubstitutionModelAdd {
subsDate: string;
remark: string;
}
The challenge is to initially populate the object with the default ISubstitutionModelAdd
interface and then add additional data based on interface T
.