Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section:

...because the response is a plain object that cannot be automatically converted to an instance of a class.

This got me thinking - what exactly does it entail to convert a plain object into an instance of a class?

Answer â„–1

This code showcases the distinction between a plain object and a class in TypeScript:

const object = {
    prop1: 'prop1',
    prop2: 'prop2'
};

The object is of type Object.

In contrast, we define a class using TypeScript syntax:

class SpecificClass {
    prop1: string;
    prop2: string;
}

The prototype of this class is SpecificClass.

Although both have matching properties with the same types, you cannot directly use the plain object as an instance of the class due to their different prototype. To convert the plain object to a class instance, you need to create a new instance of the class (in this case SpecificClass) and assign the properties from the plain object. This step involves creating a new object and setting its prototype to be that of SpecificClass.

const classInstance = new SpecificClass();
classInstance.prop1 = object.prop1;
classInstance.prop2 = object.prop2;

Now, classInstance represents an instance of SpecificClass with values equivalent to those of the plain object. The process essentially converts the plain object into a class instance. JSON to Class converters operate similarly underneath the surface.

The documentation also suggests:

Prefer using an interface over a class, especially when dealing with responses that are plain objects and cannot be directly converted into class instances.

In TypeScript, interfaces serve this purpose:

interface ISpecificObject {
    prop1: string;
    prop2: string;
}

Interfaces function differently in TypeScript compared to other statically typed languages—they employ Duck Typing to verify if an object conforms to an interface based on its structure (methods and properties). As long as the object aligns with the interface in terms of signature, it can be used seamlessly without conversion. Therefore, passing the object variable where ISpecificObject is expected is valid without any intermediate steps.

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

Solutions for accessing data variables outside of a Vue file

Utilizing Vue.js for data binding and filtering has been a rewarding experience. I've set up a Vue object within a .js file and now I aim to pass external data into it. Let's take a look at my test object testFile.js: var vm = new Vue({ el: ...

What causes the error message saying 'undefined' cannot be assigned to the specified type ...?

I just finished developing an innovative Angular application. Within the app.component.html file, I have included: <bryntum-scheduler #scheduler [resources] = "resources" [events] = "events" [columns] = "schedul ...

How can I configure Material-UI's textfield to return a numerical value instead of a string when the type is set to "number"?

Utilizing Material-UI's TextField alongside react-hook-form to monitor inputs has raised an issue for me. I have observed that regardless of the input type, it always returns a string. This creates conflicts with the data types I am using in my codeba ...

What is the best way to efficiently transmit Objects through AJAX utilizing bodyParser in node.js express?

Currently attempting to execute: $.ajax({ type:"POST", url:"/psychos", data:JSON.stringify(this.psycho) }) Upon reaching the server, I encounter the following: app.post("/psychos", function(request, respon ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

The code snippet 'onload='setInterval("function()",1000)' is not functioning as expected

I need to continuously load the contents of an XML file into a specific HTML div every second. Here is the JavaScript code that I am using to parse the XML file: function fetchEntries() { if (window.XMLHttpRequest) req = new XMLHttpRequest(); ...

Comparing "if" and "else" within the XMLHttpRequest() function will not

function banUser() { var userToBan = document.getElementById('userToBan').value; var cid = document.getElementById('chatId').value; if (userToBan.length <= 0) { var x = document.getElementById("banerror"); x.innerHTML ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

Class that can be exported with a nested object stored as a property

I am working on developing a reusable class with an object as a property in Angular 2. My goal is to allow binding my form to it using NgModel. For instance, let's say I have the following object: user: { name: string, address: { street: str ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

What is the best way to create a screen capture of a webpage using a URL?

Currently working on a Spring MVC website project, I have implemented a form requesting the user's website URL. Once entered, I aim to display a screenshot of the specified website for the user to view. Contemplating whether to generate the image on ...

JavaScript and HTML code for clipboard functionality without the need for Flash

My challenge lies in creating a grid with numerous columns and data. The user has expressed the desire for a copy to clipboard button that will allow them to easily copy the data. Can anyone suggest ways to implement Copy to Clipboard functionality withou ...

Allow only numerical values through an ion-input in Ionic 4, preventing the input of letters and special characters

I am currently developing an application in Ionic 4 that requires users to enter only integer numbers (0-9). I need to prevent any other characters such as alphabets, dots, or plus signs from being entered. However, the methods I have tried so far have not ...

Automatically refresh the browser upon changes in file content, utilizing Node.js for saving

Currently, I am immersed in a project using node.js. One of my main requirements is to be able to load a .txt file on the browser and have its content updated whenever changes are made and saved. Additionally, I would like the browser to automatically re ...

Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously. Here's an examp ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

When utilizing Md-select in Protractor, how can the dropdown list be accessed?

I am having trouble locating the option from the dropdown menu that I need to select. Despite trying various methods, I have not been successful. <md-select ng-model="card.type" name="type" aria-label="Select card type" ng-change="$ctrl.onCardSelecti ...

Creating a compact Swiper slider: reducing image size without sacrificing full window coverage!

Utilizing Swiper to craft a slider that occupies the entire window, with a slight margin for a bar-- no issues there. () However, the image I placed in for the slide () appears to be excessively enlarged. Is there a way to display more of the width of th ...