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

Exploring diverse paging methods tailored to specific devices within Angular 12

Hey there! I'm looking to implement two different paginations for a single table with 20 rows. Here's what I need: For desktop, the first pagination should display 10 rows on the first page and the remaining 10 rows on the second page. As f ...

Obtain a collection of lists stored in Firebase

As I work on creating an Ionic app with a Firebase database, my data structure in Firebase looks like the image below. I am utilizing angularfire2 to retrieve this data: https://i.stack.imgur.com/5akQf.png While I have successfully obtained the list of pa ...

Having trouble installing Angular CLI using npm command

After diligently following the steps outlined in the documentation here to install the Angular CLI, I encountered an issue. Upon running the command $ npm install -g @angular/cli in an empty directory, I was met with the following error message: npm ERR! ...

Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fi ...

Is there a way to find all records created at a particular time daily through a query?

I understand how to search for documents within a particular range, but I am unsure of the query needed to retrieve all documents in a collection that were created at 3PM. Assuming there is a field called createdAt where this information is stored as Jav ...

Tips for troubleshooting an Angular error when no specific information is provided

I'm encountering an error `ERROR Error: "[object Object]" in my console and my app is displaying a white screen. Everything was working perfectly fine before, and I can't pinpoint any changes that may have caused this issue. The error appears to ...

Analyzing npm directive

I have a script that handles data replacement in the database and I need to execute it using an npm command package.json "scripts": { "database": "node devData/database.js --delete & node devData/database.js --import" ...

What are the steps to utilize the feature of "nprogress"?

After successfully installing npm install nprogress in my project, I encountered an issue when trying to refresh the page - the console displayed the following message: hot-dev-client.js:182 [Fast Refresh] done hot-dev-client.js:196 [Fast Refresh] rebuildi ...

What is the reason behind the blocking of Ajax GET requests without CORS, while JSONP requests are permitted?

Accessing any page on the web through a GET request using HTML tags from a different origin is possible: <script src="http://example.com/user/post?txt=sample"></script> XHR requests to other origins are blocked for security reasons. For examp ...

Tips for handling CSS loading delays with icons in OpenLayers markers

When using openlayers (v4.6.4) with font-awesome as marker icons, the icons do not display upon first load (even after clearing cache and hard reload). Instead, I see a rectangle resembling a broken character. It is only on the second load that they appear ...

What is the best way to resume a Jquery function if it has not

How do I make my form alert re-trigger when the user clicks the button again if the input is still empty? What I've tried: After clicking the button, it checks if the inputs are empty and shows an alert. However, once the alert appears, if I click th ...

An error was encountered: "Uncaught SyntaxError: Unable to utilize import statement outside of a module in

I have come across the following code while learning React and trying to execute it. HTML <html> <head> <link href="index.css" rel="stylesheet"> </head> <body> <div id="r ...

Having trouble deploying Firebase Cloud function following the migration to Typescript

After following the steps outlined in the firebase documentation to convert my cloud functions project to TypeScript (see https://firebase.google.com/docs/functions/typescript), I encountered an error when attempting to deploy using 'firebase deploy - ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

"Exploring JSON data with jQuery: A guide to efficient search techniques

I have a local file containing JSON data which I successfully loaded using jQuery. My current task is to specifically find the pId with the value of "foo1". The JSON data { "1":{ "id": "one", "pId": "foo1", "cId": "bar1" }, "2":{ ...

Tips for Ensuring the Observable Completes Before Subscribing

I utilized RXJS operators in my code to retrieve an array of locations. Here is the code snippet: return O$ = this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: fal ...

What is the best approach to create a JavaScript search filter function spanning two pages?

Page1.html has a form with a drop-down menu containing options Color and Shape. There is also a submit button. Assuming Page2.html displays various shapes like Blue Square, Red Square, Blue Circle, Red Circle, is it feasible to create a JavaScript file th ...

Updating the reference path in the index.html file during Angular 6 build process

When developing an Angular 6 application, the scripts and CSS files are automatically generated with hashed values at the end of their names. I am wondering if it is possible to update the links to these files in the index.html file. Currently, they point ...

JSX tags without any inner content should be self-closed

After successfully running this code, I encountered an issue when committing it to git. The error message 'ERROR: src/layouts/index.tsx:25:9 - JSX elements with no children must be self-closing' appeared. I attempted to resolve the error by addi ...

Having trouble with the $.post method not loading my PHP file in my

I followed a tutorial on YouTube to copy the code, adjusted the database connection and SELECT items to fit my existing DB, but I'm struggling to get the JS file to load the PHP file. When I use Chrome's "inspect" tool, it shows that the JS file ...