Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance:

class BaseModel {
    constructor (args = {}) {
        for (let key in args) {
            this[key] = args[key]
        }
    }
}

class User extends BaseModel {
    name: string
}

For creating instances, I've been using the following method:

let user = new User({name: 'Jon'})

However, now I'm interested in implementing class-transformer and replacing the basics with it:

let user = plainToClass(User, {name: 'Jon'})

Since my codebase heavily relies on the initial approach, I want to integrate the new method seamlessly without disrupting existing code:

 constructor (args = {}) {
        let instance = plainToClass(CLASSTYPE, args)
        for (let key in Object.keys(instance)) {
            this[key] = instance [key]
        }
    }

The challenge is identifying the class type within the constructor. Using "User" isn't feasible since there are other classes extending from the base model.

Answer №1

One possibility is using new.target. Check out the documentation for more information.
To access the constructor, you can use new.target.prototype.constructor, and the property name will give you the class name.

class BaseModel {
    typeName: string;

    constructor (args = {}) {
        this.typeName = new.taget.constructor.name;
    }
}

class User extends BaseModel {
}

const user = new User();
const typeName = user.typeName; // This will return 'User'

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 error occurred - 0x800a1391 - JavaScript runtime error: The function 'SelectAllCheckBoxes' has not been defined

I'm currently in the process of learning web development and I am trying to incorporate jQuery into my ASP .NET page. Within the header section, I have included the necessary references: <head id="Head1" runat="server"> <link href=" ...

Remain on the React page following an HTTP POST request to Flask

Is there a way to stay on the React frontend (localhost 3000) after completing a POST request to a Flask backend from a React form, without redirecting in the Flask backend? Relevant code: export const DateForm = () => { return ( <div&g ...

"Learn to easily create a button within a table using the powerful functionality of the dataTable

I need to add a button to each row in a table. I managed to achieve this with the code below, but there's a problem - every time I switch between pages, the button keeps getting added again and again. It seems like the button is generated multiple tim ...

A Step-by-Step Guide to Launching PDF Blob from AJAX Response in a Fresh Chrome Tab

I'm sending a POST request to a server, and in response, I receive a PDF file that is returned as a blob. To handle this blob, I am using the "handle-as='blob'" attribute of iron-ajax (a Polymer element), just to cover all bases. Now, my g ...

A guide to integrating Material-UI with your Meteor/React application

I encountered an issue while trying to implement the LeftNav Menu from the Material-UI example. The error message I received is as follows: While building for web.browser: imports/ui/App.jsx:14:2: /imports/ui/App.jsx: Missing class properties transf ...

Configuring the React Typescript router to support username-based URLs should be done in a way that does not cause conflicts with other routes

I am looking to display a user's profile on a URL format such as www.domain.com/<userName> and load the component ShowProfile. I want to ensure that terms is not mistaken for a username, so if I visit www.domain.com/terms, I do not want to load ...

Using an AJAX request to edit a record directly without the need for a

When updating a record, I typically utilize CRUD operations and a store setup similar to the following: storeId: 'storeId', model: 'model', pageSize: 10, autoLoad: true, proxy: { typ ...

Troubleshoot: Issue with Navbar Dropdown Expansion on Bootstrap Sass 3.3.6 with JavaScript

Beginner: Bootstrap Sass 3.3.6 - Incorporating Javascript - Issue with Navbar Dropdown Not Expanding application.html.erb Head: <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> ...

Do we need a peer dependency specifically for TypeScript typings or is it optional?

My TypeScript library includes a React component, and one of the optional features allows users to pass an instance of a Redux store as a prop for Redux integration. <Component reduxStore={store}></Component> Since this feature is optional, I ...

Classify the JavaScript objects according to the array of object lists

Struggling to find a solution for converting this list of objects based on the group array. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups. Additionally, trying to disregard ...

Guide on retrieving the interface property name or key name as a string in Typescript

Currently, I am utilizing the API of Slack and encountering situations where I send JSON requests containing strings that return as property names later on. I want to create an interface where I can send one of its property names as a string and receive t ...

I'm looking for guidance on how to properly implement onChange in this particular script. Any help with the correct syntax

Can someone help me with the correct syntax for writing onChange in this script? I want to integrate these phpcode into my script. Here is the Javascript code: ih+='<div class="form-group drop_bottom" id="select_one_'+extra_num+'">< ...

What is preventing me from concealing my input field when its type is set to "file"?

I've been attempting to conceal my input field of a file type, but even with the hidden attribute, it refuses to hide. Interestingly, once I remove type="file", the code successfully hides itself Does anyone have insight on how I can hide ...

Effectively enhance constructor by incorporating decorators

Is it possible to properly extend a class constructor with decorators while maintaining the original class name and static attributes and methods? Upon reading the handbook, there is a note that cautions about this scenario: https://www.typescriptlang.or ...

Execute tests on changing files using cypress.io

I'm currently experimenting with using Cypress to test a large Angular application that I've developed. What I want to achieve is to load an expectation file into my test and then run the test based on this expectation file. Despite trying diffe ...

Variable missing in the ExpressJs view

Hey there! I'm new to Nodejs and currently experimenting with it. I've been trying to convert some of my basic Python codes to JavaScript. In one of my projects, I am sending a get request to the YouTube API and receiving 50 results in JSON forma ...

What is the best way to refresh the slick jQuery plugin for sliders and carousels?

I am currently facing an issue with two buttons that have the same function. The purpose of these buttons is to retrieve data from an API, convert it to HTML, and then append it to a <div> using jQuery. Finally, the data is displayed using the slick ...

Error: Authorization requires both data and salt arguments

As a novice in NodeJS, I attempted to create an authentication form using NodeJS + express. The issue I am facing is regarding password validation - specifically, when "confirmpassword" does not match "password", it should return nothing. Despite my effo ...

Using Python with Selenium and JavaScript for Logging in

When using Selenium and Python, I am attempting to log in to a website but encountering difficulties. The issue is that the source code does not display the necessary Id=apple_Id required for sending login information, although it can be seen when inspecti ...

Retrieving information from a dynamically generated HTML table using PHP

I have successfully implemented functionality using JavaScript to dynamically add new rows to a table. However, I am facing a challenge in accessing the data from these dynamically created rows in PHP for database insertion. Below, you will find the HTML ...