Error occurred while creating a new instance of a generic object

I´m encountering a

TypeError: type is not a constructor
when attempting to convert API data into Frontend DTOs.

The transformation method is as follows:

transform<T>(entities: any[]) {
    const tableDtos = new Array<T>();
    for (const entity of entities) {
      const dto: T = this.factory.createEntity(entity);
      tableDtos.push(dto);
    }
    return tableDtos;
  }

My factory looks like this:

export class Factory {
  create<T>(type: (new () => T)): T {
    return new type();
  }
}

I found the solution here. What could I be missing?

DTO

import { Entity} from 'src/models/api/Entity';

export class EntityTableEntry {

  id: number;
  name: string;

  constructor(entity: Entity) {
    this.id = entity.ID;
    this.name = entity.Name;
  }
}

Entity

export interface Cost {
  ID: number;
  Name: string;
  Description: string;
  Value: number;
}

The reason behind wanting a generic method is to avoid rewriting the transform method for each API call, which can become messy!

Answer №1

Assuming that the entities variable contains the necessary data for creating objects, it cannot be invoked using new. Instead, you should provide the actual class you wish to instantiate (perhaps by assigning the data to a new instance):

class xx {
  factory: Factory = new Factory();
  transform<T>(type: (new () => T), entities: any[]) {
    const tableDtos = new Array<T>();
    for (const entity of entities) {
      const dto: T = this.factory.createEntity(type, entity);
      tableDtos.push(dto);
    }
    return tableDtos;
  }
}

class Factory {
  createEntity<T>(type: (new () => T), data: any): T {
    var r = new type();
    Object.assign(r, data) // suggesting a possible implementation 
    return r;
  }
}

class DataClass { a!: number }

var r = new xx().transform(DataClass, [{ a: 1 }]);
console.log(r);

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

An effective way to extract targeted information from an array of objects using Typescript

I'm having trouble extracting the IDs from the selected items in my PrimeNG DataTable. Despite searching on Google, I couldn't find much information about the error I'm encountering... ERROR in C:/Users/*****/Documents/Octopus/Octopus 2.0/s ...

Generic Abstract Classes in TypeScript

In my TypeScript code, I have an abstract generic class with a method that takes a parameter of a class type variable. When I tried to implement the abstract method in a derived class, I noticed that the TypeScript compiler doesn't check the type of t ...

The Angular template is throwing an error stating that c_r1.getCatType is not a valid function

Within my Angular project (version 9.1.0), I have a class structured like this: export class Contract { contractName: string; limit: number; public getCatType(): string{ if(this.limit > 0) return 'p'; return &ap ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

The module does not contain 'toPromise' as an exported member in rxjs version 5.5.2

Encountering an error when using toPromise Prior method: import 'rxjs/add/operator/toPromise'; Updated approach: import { toPromise } from 'rxjs/operators'; The new way is causing the following issues: [ts] Module '"d:/.../ ...

Mastering Angular 2 Reactive Forms: Efficiently Binding Entire Objects in a Single Stroke

Exploring reactive forms in Angular 2 has led me to ponder the possibility of binding all object properties simultaneously. Most tutorials show the following approach: this.form = this.fb.group({ name: ['', Validators.required], event: t ...

When importing a module, the function in the ts file may not be recognized or located

While attempting to create a VSTS (Azure Devops) Extension, I encountered a perplexing issue. Within my HTML page, I have a button element with an onclick listener: <!DOCTYPE html> <head> <script type="text/javascript"> VS ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

Is it feasible to incorporate a multi-level navigation menu into the "NavItem" component using MaterialUI with TypeScript?

Instructions for creating a multi-level navigation menu using MaterialUI and TypeScript: To the existing '/questions' section, it is desired to include the following 2 navigation menus: /questions/Tags /questions/Users This should resemble the ...

Directive for masking input values

I am in need of an input that adheres to the following format: [00-23]:[00-59] Due to the limitations of Angular 2.4, where the pattern directive is unavailable and external libraries like primeNG cannot be used, I have been attempting to create a direct ...

Encountered an issue with valid types while executing the following build

Encountering an error when attempting to run the next build process. https://i.stack.imgur.com/qM3Nm.png Tried various solutions including updating to ES6, switching the module to commonJs, downgrading webpack to version 4 with no success. The only worka ...

Issue with Typescript Application not navigating into the node_modules directory

After attempting to load the app from the root directory of our server, it became clear that this was not a practical solution due to the way our application uses pretty URLs. For instance, trying to access a page with a URL like http://www.website.com/mod ...

When attempting to parse a file name using a regular expression in TypeScript (or even plain Node.js), the unexpected outcome is a

Looking to extract language information from a filename? Check out this simple construct: The structure of my language.ts model is as follows: export interface Language { language?: string; region?: string; } The function designed for parsing the fi ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Issue: The function (0, react__WEBPACK_IMPORTED_MODULE_1__.useActionState) is not recognized as a valid function or its output is not iterable

I found a great example of using useActionState at this source. Currently, I am implementing it in my project with Next.js and TypeScript. app/page.tsx: "use client"; import { useActionState } from "react"; import { createUser } from ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

Investigating TypeScript Bugs in Visual Studio Code

As I navigate through various sources, I notice that there is a plethora of information available on older versions of VSCode (v1.16.1 - the most recent version at the time of writing) or deprecated attributes in the launch.json file. I have experimented ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

Prompt the user to take an action by opening a modal or dialogue box from a dropdown menu

I am looking to implement a functionality where a modal or dialogue will be opened when a user selects an option from a dropdown menu. As the dropdown menu will have multiple options, different dialogues/modals should appear based on the selected option. ...

Issue with directive implementation of regex test as attribute - validations in typescript and angular

I am currently working on a project to create a module with custom validation directives. These validations are implemented using regular expressions (regex). The specific error I encountered is: Error: [$injector:unpr] Unknown provider: REG_EXPProvid ...