I have many classes extending an interface. These classes can have arrays containg objects of each other. So for instance: A school can contain many studens but both implements the same interface.
I've create a generic function for this instead of using every time a forEach loop and pushing them to the array. This new generic function should do this for me with a single line.
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;
}
But TypeScript/Angular is giving me an error because of the T. I'm not allowed to create an instance of T. So how can I do this?