Creating a new instance with a parameter in TypeScript using a generic function

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?

Answer №1

During runtime, types are erased causing T to be removed and transforming the expression new T(item) into new (item), which does not logically make sense. In simpler terms, types cannot be used in expressions.

The solution is to provide a constructor function (i.e., the class) as an argument to your mapping function:

interface MyInterface { }
export class School implements MyInterface {
    public students: Student[] = [];
    public constructor(data_from_backend: any) {
        this.students = mapDataToModelArrayFunction(Student, data_from_backend.students);
    }
}

export class Student implements MyInterface {
    public name: string;
    public constructor(data_from_backend: any) {
        this.name = data_from_backend.name;
    }
}

export function mapDataToModelArrayFunction<T>(cls: new (data: any) => T, array: any[]): T[] {
    const listToReturn: T[] = [];
    if (Array.isArray(array)) {
        array.forEach(item => {
            listToReturn.push(new cls(item));
        });
    }
    return listToReturn;
}

Play

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can errors be captured when working with chained rxjs observables in an combineLatest scenario?

After reading through this thread, I encountered the following scenario: Observable.combineLatest( this.translate.get("key1"), this.translate.get(""), this.translate.get("key3"), this.translate.get("key4") ) .subscr ...

What could be causing my Bootstrap accordion to not expand or collapse within my Angular application?

Struggling with my Accordion Angular component that utilizes Bootstrap - the collapsing and expanding feature isn't functioning properly. I've simply copied the bootstrap code into my accordion.component.html. <div class="accordion accord ...

ViewChild with the focus method

This particular component I'm working on has a hidden textarea by default : <div class="action ui-g-2" (click)="toggleEditable()">edit</div> <textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea f ...

Tips for enabling autofocus in mat-select列表。

I am working on an angular project where I am using Angular Material and a mat-select element. In my form, the mat-select is the first element, and I want to set auto-focus on it when the page loads. However, I have been facing some difficulties achieving ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

Is it possible to determine the time format preference of the user's device in Angular? For example, whether they use a 24-hour system or a 12-hour system with AM

In Angular, is there a way to determine whether the user's time format is set to 24-hour or 12-hour system? Any help would be greatly appreciated. Thanks! ...

Accessing node_modules in TypeScript within an Asp.Net Core application

As I work on building a straightforward ASP.NET Core application utilizing npm and TypeScript, the structure of my project is organized as follows: / root | wwwroot | js | AutoGenerated // <-- TS output goes here | view | i ...

What is the best way to subscribe to both the URL and parameters in the ActivatedRoute?

When the url changes, <code>activatedRoute.url.subscribe provides a list of urlsegments. Additionally, activatedRoute.queryParams.subscribe delivers an object of queryParams when they change. Is there a way to subscribe to both simultaneously in ord ...

Access Element in Array by Type using TypeScript

Within a TypeScript project, there exists an array of containers that possess a type attribute along with supplementary data based on their individual types. type Container<Type extends string> = { type: Type; } type AContainer = Container<" ...

"An error occurred in Angular due to the absence of a defined user

Creating a variable boolean isEdit in Angular8 to differentiate between add and edit functionalities. Hello, I am looking to edit in angular8 by setting up a boolean variable isEdit for distinguishing between adding and editing. Greetings! Currently work ...

ngModelChange not triggered when updating the model from a component

I am currently exploring Angular and trying to grasp the concept of connecting different controllers to update their values based on changes in one controller. In a specific scenario, I have a form with ngModel and I am attempting to utilize ngModelChange ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

Issue with linear Graham scan method causing failure when computing convex hull of basic polygon

It is said that the Graham scan algorithm can efficiently find the convex hull of a simple polygon in linear time without requiring the nlogn sorting step since the vertices are already effectively sorted. I have implemented the Graham scan algorithm, and ...

"Unleash the Power of Go HTTP Server for React, Angular, and

Recently, I developed a small HTTP Server in GO specifically for static files: func wrapHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(srw, r) log.Printf("GET %s", r.RequestU ...

How do I adjust brightness and contrast filters on a base64 URL?

When presented with an image in base64 format like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg== What is the most efficient method to programmatically alter a filter (such as brightness or cont ...

Unable to utilize object functions post-casting操作。

I've encountered an issue while trying to access some methods of my model object as it keeps returning an error stating that the function does not exist. Below is the model class I have created : class Expense { private name: string; private ti ...

What is the best way to transfer information to the canActivate service guard?

Here is the route definition: { path:'specific_path', component: specific_component, canActivate: specific_service} What is the best way to send data to the specific_service? ...

Choosing the correct key and handling parsing errors

As I work on converting a class component to TypeScript, I encountered an error while trying to implement one of my onChange methods. The error message stated: "Argument of type '{ [x: number]: any; }' is not assignable to parameter of type &ap ...

Error occurred in child process while processing the request in TypeScript: Debug Failure encountered

I encountered the following error in TypeScript while running nwb serve-react-demo: Child process failed to handle the request: Error: Debug Failure. Expression is not true. at resolveNamesWithLocalCache (D:\Projects\react-techpulse-components& ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...