How can I reference MyClass.new as a method in Typescript?

Within my code, I have an array of objects and each object is structured like this:

{ id: 'string', name: 'string' }

There's a class defined as follows:

class User {
  constructor(obj: Record<string, string>) {
    Object.assign(this, obj);
  }

  id: string; 
  name: string;
}

The goal is to utilize the Array.map() method to generate a new array containing instances of the User class:

const users = userObjects.map(o => new User(o));

While the current implementation works, it seems inelegant. Is there a way to directly reference the new keyword for the User constructor and eliminate the need for the arrow function?

I'm uncertain if the approach varies between Javascript and Typescript (although I suspect it doesn't), but just to clarify, I am working within a Typescript environment.

Answer №1

Unfortunately, there is no direct method available to achieve this functionality. However, you could potentially create a utility function that acts as a workaround, essentially abstracting the existing process. The crux of the matter lies in the absence of a specific `new` method (akin to Java's `User::new`). Instead, the existence of the `User` function itself determines whether it generates a new `User` instance or triggers an error when called. In modern environments, invoking it with `new` or similar constructs like `Reflect.construct` will result in the creation of a `User` instance. Conversely, calling it directly would lead to an error (in ES2015+; although in ES5 compilation, it may not throw an error but also won't function correctly).

The alternative solution you have implemented using a wrapper arrow function is indeed a valid approach and likely what I would recommend as well.

If you find yourself needing this functionality across multiple instances, integrating a static method within the `User` class could prove beneficial:

class User {
    // ...
    static create(...args) {
        return new User(...args);
    }
}
// ...
const users = userObjects.map(User.create);

(It's worth noting that the `create` method may not operate as expected in subclasses of `User` [depending on your criteria for "proper functionality"], as it always generates a `User` instance regardless of being invoked as `UserSubclass.create(/*...*/)`). Typically, leveraging `this` instead of `User` (`new this(...args)`) might seem unconventional but can work effectively if the call accurately sets `this` [such as with `User.create(/*...*/)` or `UserSubclass.create(/*...*/)`]. Nonetheless, due to `map` inadequately handling `this` context, this approach fails unless you either bind `create` or remember to pass the second argument to `map` [`.map(User.create, User)`]). Therefore, reverting back to utilizing a wrapper arrow function appears to be the more pragmatic choice.)

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 to create an AngularJS Accordion with dynamic is-open attribute using ng-repeat

Even though I can get it to work without using ng-repeat, the issue arises when I have a list of elements and is-Open doesn't function properly. 1. It should only open one panel at a time (sometimes it opens all) 2. The value of is-Open should be ...

Ways to retrieve the identifier of an iframe

document.getElementById(Iframe_id).contentWindow.addEventListener("blur", blurtest, true); This line of code assigns the blur event to an iframe and it is functioning properly. However, when in function blurtest(e) { alert(e.target.id); } An alert ...

Storing Data in an Array Using MongoDB's $push Method Depending on a Variable's Value

I'm attempting to add an item to my MongoDB record in Node (using MongoJS) by using the $push method. Here is an example of how it's done: exports.saveToUser = function (req, res) { console.log("IN"); var user = req.params.user; var ...

What is the best way to extract and count specific values from a JSON file using JavaScript?

My JSON data looks like this: /api/v1/volumes: [ { "id": "vol1", "status": "UP", "sto": "sto1", "statusTime": 1558525963000, "resources": { "disk": 20000000 }, "used_resources": { "disk": 15000000 }, "las ...

Methods for removing and iterating through images?

I successfully programmed the image to move from right to left, but now I want to add a function where the image is deleted once it reaches x: 50 and redrawn on the left. I attempted to use control statements like "if," but unfortunately it did not work a ...

Restarting an Angular app is necessary once its HTML has been updated

I've encountered an interesting challenge with an application that combines MVC and Angular2 in a not-so-great way. Basically, on the Index page, there's a partial view loading the Angular app while also including all the necessary JavaScript li ...

Troubleshooting issue with Highcharts 3D rendering after using setState()

When working on implementing a 3d pie chart in React using react highchart, I encountered an issue. Whenever I utilize this.setState() inside the lifecycle method componentDidMount(), the 3d chart shifts from its original position to the right diagonally. ...

What is the mechanism behind sprites in three.js?

I've encountered a problem with my scene that includes numerous sprites and results in a poor frame rate. I attempted to improve performance by reducing sprite resolution and adjusting camera limitations for render distance, but unfortunately, it had ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

What could be causing the issue of my application not being able to operate on the specified port on Heroku?

After spending two whole days trying to decipher the Heroku error message with no success, I'm still unable to pinpoint what is causing the issue. 2021-07-18T04:27:08.741998+00:00 app[web.1]: {"level":30,"time":1626582428741,&quo ...

JavaScript will not prevent PHP form submissions from executing

I am currently facing an issue with JavaScript where it displays an error window, but surprisingly does not prevent the form submission. I have been trying to figure out what exactly is causing this problem without much success. Below is the code I am work ...

The function navigator.canShare() encountered a permissions denial while running in Typescript

Currently, I am in the process of developing an Angular8 PWA and have successfully implemented webshare to share text content. To my excitement, Chrome has now extended its support for file sharing starting from May 2019. However, while attempting to int ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...

effective ways to extract objects from nested structures using a specific identifier

In this sample data, I am looking to filter an object based on its ID key let myData = { "nodeInfo": { "9": { "1": { "ID": "14835" ...

My Vue frontend project is encountering an error during compilation that states "this relative module module was not found."

I have created a vue frontend to interact with my spring backend, which is working well. However, when I compile the frontend, it compiles to 98% and shows an error message: ERROR Failed to compile with 1 error 11:24:51 The relative module was not foun ...

Removing a Request with specified parameters in MongoDB using NodeJS

Working with Angular 4 and MongoDB, I encountered an issue while attempting to send a delete request. My goal was to delete multiple items based on their IDs using the following setup: deleteData(id) { return this.http.delete(this.api, id) } In order ...

A guide on assigning a state variable to a dynamically generated component within a React application

I need to display user data from an array and have a button for each watchlist that deletes it. Although the backend is set up with a function deleteWatchlist, I am facing an issue in setting the state of the watchlistName for each watchlist after mapping ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...

Placing an eye icon on the password input field for optimal visibility and positioning

I am currently working on a Node.js project and I am attempting to incorporate an eye icon using Bootstrap into the password input field for visibility. Below is the code snippet of my input field: <div class="container"> <form ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...