Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code:


import {plainToClass} from "class-transformer";
import UserDto from "../../auth/dto/user.dto";

class JsonConverter {
    
    convertData(data) {
        return plainToClass(UserDto, data);
    }
}

However, when I try to make the class more generic,


import {plainToClass} from "class-transformer";
import UserDto from "../../auth/dto/user.dto";

class JsonConverter<T> {

    convertData(data) {
        return plainToClass(T, data);
    }
}

I encounter the following error:

T only refers to a type, but is being used as a value here

Answer №1

Upon further examination of the code, I discovered that TypeScript generics have significant differences compared to C# or other programming languages. In order to achieve a more generic feel without altering the syntax, I made adjustments to the code as follows:


import {plainToClass} from "class-transformer";

interface IClass {
    new (...args : any[])
}

class ConvertJson {

    constructor(private dto : IClass) {
    }

    userData(data) {
        return plainToClass(this.dto, data);
    }
}


I opted for using IClass instead of any to ensure consistency among team members by enforcing the usage of classes over other types.

Answer №2

Building upon the insights shared by Milad👇
class-transformer offers a set of generic classes to achieve similar functionalities as previously mentioned.

import { plainToClass, ClassConstructor } from "class-transformer";

class ConvertJson {
    userData<TargetClass>(data: unknown, dtoClass: ClassConstructor<TargetClass>) {
        return plainToClass(dtoClass, data);
    }
}

The version of class-transformer I am using is v0.5.1

✍Please take note:
plainToClasss has been deprecated❌
Instead, opt for plainToInstance (they are functionally equivalent)✅

Answer №3

It appears that the desired action is to convert the output based on the type of input.

class JsonConverter<T> {
    convertData(data) {
        return <T>parseToClass(data);
    }
}

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

Transforming functions into a new typed object with different function signatures

I am currently updating some React/Redux code that previously followed an older pattern to a more modern "hooks" based approach, using TypeScript. In the old pattern, we utilized "class-based" components and passed their "dispatch" functions using mapDisp ...

Send a function as a parameter to another component, but it remains dormant

I am attempting to control the enable and disable state of a button based on changes in a value. To achieve this, I have defined a model as follows: export class Model{ label:string=''; isEnabled:Function=()=>true; } The component1 i ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

Ways to remove a

After creating an npm link within a local dependency and then deleting that dependency from my hard drive, I am now attempting to remove this npm link. I have attempted the following steps: npm rm --global dependency npm uninstall dependency npm unlink - ...

The error message "ECONNRESET" occurred while attempting to send a post request using Axios to

Attempting to send a post request to my webserver using axios, I have a client that collects user input to populate an array of strings. This data is then sent via a post request using axios for processing by the server: if (parsedInput > 0 &&am ...

I'm curious about the significance of this in Angular. Can you clarify what type of data this is referring

Can anyone explain the meaning of this specific type declaration? type newtype = (state: EntityState<IEntities>) => IEntities[]; ...

Strange appearance of Material UI input field

https://i.stack.imgur.com/az6wt.png Does anyone have an idea why this problem is occurring? When using material UI, the default value and label for the field seem to be overlapping. Below is the code for rendering the fields: {formSchema.map((element, i ...

What is the best way to utilize multiple models under a single root in ReactJS?

Greetings! I currently have a root structure in the following code snippet: <body> <noscript>You need to enable JavaScript to run this app.</noscript> <button >Platform</button> <button >Game</button> < ...

Prevent assigning values to rxjs observables recursively

I am seeking suggestions on how to enhance the code provided below. I will outline the issue and present my current solution, which I aim to refine. The code is written in Angular 4 (TS). herelistOfItems$: Observable<Array<Item>>; // Fetchin ...

Using Angular to Make a Request for a Twitter API Access Token

I'm facing some challenges while trying to implement a Twitter Sign-In method for my angular app. The issue seems to be with the initial step itself. I am attempting to make a post request to the request_token API by following the steps outlined at th ...

Having trouble installing sqlite3? Encounter an issue like this: "srcdatabase.cc(35): error C2248: 'Napi::Env::DefaultFini': cannot access private member declared in class 'Napi::Env'"?

Encountering issues while trying to install sqlite3 for a Strapi app I've attempted using yarn to install sqlite3 in various ways, but to no avail. Below is the error log: Error message: Issue with installing sqlite3 when creating a Strapi app (..& ...

An AJAX script for dynamically adding, modifying, and removing records from a database

How can I implement a functionality where by pressing "-" the vote is removed from the database, and when any other number is selected, the vote will be updated in the database with that value? The default value of the dropdown list is votacion.votCalific ...

Tips for successfully transferring data using a dynamic key in a Semantic UI Vue dropdown

My current challenge involves troubleshooting the semantic-ui-vue dropdown functionality. To view the issue, visit my sandbox link: https://codesandbox.io/s/3qknm52pm5. Within the sandbox environment, there are two dropdown menus labeled as From and To. ...

Tips for maintaining knowledge after redirecting to a new page

Building an app using Ionic 4 where I need to display vouchers from a database as images. Each image should act as a link to a details page showing more information about that specific voucher. However, I am struggling to figure out how to keep track of th ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...

Discovering the smallest and largest values in an object literal using JavaScript

I am looking to extract the minimum value from an object literal and utilize it in AngularJS, as shown below: scope.data = { 'studentName' : "Anand", 'socialStudies' : "98", 'english' : "90", 'math' ...

Is JavaScript still running despite not displaying insecure items due to IE 8 security warning?

After a user completes a transaction on my site, the confirmation page displays Google conversion tracking code in a small JavaScript snippet. This code is located on my Wordpay callback page, which pulls data from the regular site (HTTP) to the Worldpay s ...

Having trouble integrating MaterialUI Datepicker, Dayjs, useFormik, and Yup

Currently, I am facing a recurring issue with the Material UI Date picker in conjunction with day js. The problem arises when I select a date on the calendar for the first time, it updates correctly in the text field but fails to work thereafter. Additiona ...

Surprising block of text suddenly popped up on the browser screen while I was in the middle of working on

Currently delving into the world of MERN stack and working on a simple project. Everything was going smoothly on localhost until out of nowhere, some garbled text appeared on the screen, hindering my progress. I'm completely stumped as to what this my ...

Clear the modal form in Codeigniter and AJAX upon closing the edit modal

Having an issue with my modal form - when I open the edit modal, the data is fetched and that part works well. However, when I close the modal and try to add a new user, the data is automatically fetched again. Why is this happening? Shouldn't the for ...