In my code, I have numerous classes that extend an interface. These classes can contain arrays of objects from each other. For example, a school can have multiple students, but both classes implement the same interface.
To streamline this process, I decided to create a generic function instead of manually using a forEach loop and pushing items into the array each time. This new generic function should handle everything in just one line of code.
export class School implements MyInterface {
public studens: Student[] = [];
public constructor(data_from_backend) {
this.students = mapDataToModelArrayFunction<Student>(data_from_backend.students);
}
}
export class Student implements MyInterface {
public name: string;
public constructor(data_from_backend) {
this.name = data_from_backend.name;
}
}
export function mapDataToModelArrayFunction<T>(array): T[] {
const listToReturn: T[] = [];
if (Array.isArray(array)) {
array.forEach(item => {
listToReturn.push(new T(obj));
});
}
return listToReturn;
}
However, TypeScript/Angular is throwing an error due to the use of T. It seems I am not permitted to instantiate an object of type T. So, how should I go about resolving this issue?