What is the syntax for invoking a javascript/typescript constructor while providing an object as an argument?

How should I structure my constructor if it will be invoked with the following code:

const user = new User({
    username,
    email
})

Both `username` and `email` are of type string.

Update:

Here is how you can implement this in TypeScript:

interface UserData {
  username: string;
  email: string;
}

class User {
  username: string;
  email: string;
  
  constructor({ username, email }: UserData) {
    this.username = username;
    this.email = email;
  }
}

const user = new User({
  username: "exampleuser",
  email: "user@example.com"
});

console.log(user);

Answer №1

Successful Code Implementation !!

using JavaScript

class Person {
  constructor({name, gender}) {
    this.name = name;
    this.gender = gender;
  }
}
const name = 'John';
const gender = 'male';
const person = new Person({
  name,
  gender
});
console.log(person);

switching to TypeScript

interface Details {
  name: string;
  gender: string;
}

class Person implements Details {
  constructor({ name, gender }: Details) {
    this.name = name;
    this.gender = gender;
  }
}
const name = 'John';
const gender = 'male';
const person = new Person({
  name,
  gender
});

console.log(person);

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 Exclude Box Geometry from Merged Geometry in THREE JS

I have over 100,000 boxes that I've added to a merged geometry. Occasionally, I need to remove some geometries from this merged structure. Is it possible for me to iterate through the position attributes in increments of either 108 or 72 vertices per ...

Prisma encountered an error with the database string: Invalid MongoDB connection string

I'm encountering an issue with my MongoDB data provider, as I am informed that my connection string is invalid. The specific error message states: The provided database string is invalid. MongoDB connection string error: Missing delimiting slash betw ...

Attempting to create a tracker that increments every time a form input field is filled out using React in conjunction with Formik

I am attempting to develop a function that will increase every time a user enters information into a field. Within my existing setup, I have a parent component with a state containing a counter value initialized to 0. My child component is a Formik contai ...

Using AngularJS to prevent HTML injection in input fields

Is there an effective method to prevent HTML injection in input fields? As an example, if I have a search input field: <input id="search" type="text" ng-model="search" placeholder="search..."> I want to ensure that any attempts to input malicious c ...

What is the best way to bring Axios into the main.js file in a Vue project?

Recently, I encountered an issue with using axios in my Vue project. An error message stating that 'axios' is not defined popped up when I attempted to use axios.get() in my Home.vue file. I'm wondering if the problem lies within my configur ...

A guide on the correct way to cast ObjectIds in Mongoose

I've encountered a problem with casting ObjectId in express.js using mongoose. In my route, I've attempted both casting before and using req.params.id directly, but nothing seems to be working. I'm certain the id is correct as I've tri ...

Using NodeJs to pass values to a callback within a condition statement and retrieve the returned value

Within my routing file, I have implemented a condition where an external function is used to compare two values: obj.id === getId. Based on whether this condition evaluates to true or false, the view is rendered, or the user access is blocked. The functio ...

When utilizing jQuery version 1.10.2, the HTML markup shows up prior to the page completing its loading process

I am trying to import one HTML page into another, but when I load or refresh the page, the HTML markup appears before the page fully loads. How can I fix this issue? <head> <script type="text/javascript" src="js/jquery-1.10.2.js" ></scr ...

Monitoring the initiation and completion of web requests within the Ionic framework

Currently utilizing the ionic framework in conjunction with Angular JS. In need of assistance on how to monitor the initiation of a web request. To handle the completion of a request, I have created a directive with an onLoad attribute. Here is the exam ...

How can I efficiently add multiple items to an array and store them in async storage using React Native?

I am trying to store multiple elements in local storage using React Native. I found some helpful documentation on how to do this here. Could someone guide me on the correct way to achieve this? Here's a snippet of my code: My current approach const ...

Rapid lettering with Three.js

Attempting to etch text onto a surface using Three.js has been successful, thanks to the use of csg.js and ThreeCSG. The outcome is impressive, however, the process is time-consuming, taking approximately 30 seconds on my PC to engrave the word "Hello." A ...

Creating JavaScript code using PHP

In my current project, there is a significant amount of JavaScript involved. I'm finding that simply generating basic strings and enclosing them within "<script>" tags may not be the most efficient approach. What are some alternative methods fo ...

Receive the button click event outside of the canvas

Is there a way to have separate click events for the button and the ListItem? My focus is on the button click event only, without triggering the ListItem event. Live DEMO import React from "react"; import ReactDOM from "react-dom"; import ListItem from ...

Working with JSON parsing in AngularJS without a specified element name

I am looking to extract data from a JSON response containing Country & State information. Here is the URL for the JSON data: { "China": [ "Guangzhou", "Fuzhou", "Beijing", "Baotou", "Hohhot", "Guiyang", "Yinchuan", "Nanjing", "Changzhou", "Chuzhou" ...

Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received: function m ...

Strategies for accessing the initial portion of an AJAX response

When using ajax to call an URL with dataType HTML, the response includes two parts such as accesstoken=1&expires=452. In this scenario, only the access token is needed. Using alert(response) displays both parts. How can the access token be extracted? ...

Incorporating JQuery UI Resizable functionality into a Meteor project after creating an object

After adding an object to a list of JQuery Resizable objects in my Meteor app, I noticed that the object doesn't become resizable until I refresh the page. I'm wondering what kind of event listener or solution should be implemented and where it ...

React event handling

Currently, I am in the process of developing an accordion app using React. The data for this app is fetched from an API, and while I have the basic structure of the app ready, I am facing some difficulties with handling the click event on the accordion. H ...

What is the method for sending one URL as a parameter within another URL?

When I try to access the route /new/:url with a request like /new/https://www.google.com, the response is Cannot GET /new/https://www.google.com. What I actually want to receive is the string https://www.google.com. I came across an answer on URL compone ...

Building NodeJS Applications with Object Oriented Design

After spending a considerable amount of time working with NodeJS, I am still struggling to grasp the concept of object-oriented design within the language. The closest I have come is creating a class like this: var SomeClass = function(){ var self = t ...