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

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Manage the number of choices available on a drop-down selection form

I am working with a PHP variable $a of an integer type. Based on the value assigned to $a, I want certain options to be visible in a form. For example, if $a=1; then only the first two options should be displayed, and if $a=2; then the first three option ...

Transmitting form information to a nested page within a div container

This is my fourth attempt to seek an answer to this question, as I've faced downvotes in previous attempts. So here we go again. I am trying to send data from a hidden input within a form using ajax. The value of the hidden input is generated by a php ...

Encountering a Forbidden Error with Superagent

Here is the content of my index.js file I am attempting to fetch a response from a sports data API. I can successfully send curl requests to it, but when trying this method, I encounter a 403 forbidden error. var express = require('express'); v ...

Problem: Repeated attempts to open the popup are unsuccessful

Developed a leaflet map featuring markers that open popups when clicked. Also integrated a search bar for marker searchability. However, encountering an issue where each popup can only be opened once and on selecting a marker name, the zoom functionality w ...

When an onClick event is triggered in jQuery, generate a certain number of div blocks based on the available list items, such as image source and heading text

Is it possible to generate input fields dynamically based on a dynamic list with checkboxes, labels, text, images, etc.? I currently have a working solution for checkboxes and labels using the code snippet below: let $checkboxContent = $('.checkboxes ...

Trouble With OnClick and On/Off Class Script Functionality in Chrome and Internet Explorer

I am working on a page with two iframes and a basic navigation bar. The navigation bar links are set up to target one of the iframes and replace its content when clicked. However, I am having trouble highlighting the currently selected link in the iframe - ...

JavaScript Mouseover Custom Trigger with d3.js Library

Currently, I am experimenting with d3.js and am interested in creating a custom event with a unique trigger. From my understanding, the 'mouseover' event occurs when the mouse pointer hovers over a specific element both horizontally and vertical ...

Exploring Angular2's ability to interpret directive templates using the ng-container

Recently delving into angular2, I ventured into creating dynamic forms and generating fields by following the guide provided in this URL. The result was as expected. The dynamic form component renders each field one by one using ng-container, like shown b ...

Utilize FormData by passing it to a separate function and then utilizing it

I have encountered a perplexing issue with my Flask app that involves submitting a form to upload an image to the server. Despite my efforts, I have been unable to find a solution on my own. When I submit the form, I use FormData to create the necessary o ...

Exploring the advantages and disadvantages of using React class property initializers

When building components with React, there are different ways to initialize state. One common method is using the constructor like this: class Foo extends Component { constructor() { super(); this.state = { count: 0 }; } } If you need to ini ...

What is the best way to incorporate a new attribute into an array of JSON objects in React by leveraging function components and referencing another array?

Still learning the ropes of JavaScript and React. Currently facing a bit of a roadblock with the basic react/JavaScript syntax. Here's what I'm trying to accomplish: import axios from 'axios'; import React, { useState, useEffect, useMe ...

Which method is optimal for organizing tree categories and linking them to posts, as well as locating posts based on a selected category within a MERN stack

Currently, I am utilizing the MERN stack for my project development. The project involves a tree category structure as outlined below: {id: { type: Number }, parent_id: { type: Number }, name: { type: String }, sub: { type: Boolean }} For ...

history.js - failure to save the first page in browsing history

I have implemented the history.js library to enable backward and forward browser navigation on an AJAX products page triggered by clicking on product categories. While I have managed to get this functionality working smoothly, I am facing a particular iss ...

Displaying JSON as a table using React JS

I can't seem to display JSON data in a table using the useState hook in React, and I'm not sure why. Here's a snippet from my React file: {` import React, { useState } from 'react' import "../styling/Classes.css"; import data ...

Heroku deployment failed: Push rejected due to lack of a Cedar-supported application

Trying to deploy my 3D game (created with three.js) on a Heroku server has brought up an issue. After running the command "git push heroku master," I encountered the following problem: Initializing repository, done. Counting objects: 252, done. Delta com ...

Execute an AJAX function to monitor a JSON response at intervals of 3 seconds

I'm looking to verify if my user has been updated from another system using JavaScript. Can anyone assist me in creating a function that can analyze a JSON response and determine if it is true or false? The URL /user/updatecheck/ provides a JSON res ...

Are you unsure whether to use Ajax or jQuery? If you need assistance in adding parameters to

Currently delving into ajax/jQuery and encountering some hiccups. Here's the code snippet: .click(function() { var period = 'ALL'; if ($('#registerat input:checked').val() != 'ALL') period = ...

Transform the characters within a string into corresponding numerical values, calculate the total sum, and finally display both the sum and the original string

I'm looking to convert a string containing a name into numerical values for each character, ultimately finding the sum of all characters' numerical values. Currently, only the first character's value is being summed using .charAt(). To achie ...

What is the best way to utilize Gulp and Browserify for my JavaScript application?

Looking to modernize my app with a new build system and I could use some guidance. It seems like I need to shift my approach in a few ways. Here's the current structure of my app: /src /components /Base /App.jsx /Pages.jsx /. ...