Should I use Object.assign or define class properties?

Currently in the process of developing an angular application that interacts with the twitch API. The API returns data in various formats, some of which I need to parse and save into specific classes.

My main concern is understanding the potential drawbacks of using Object.assign to create an instance of a class as opposed to manually assigning properties from deserialized JSON data?

Here's what I have implemented so far:

export class UserDetails implements Serializable<UserDetails>{
    public _id: number;
    public bio: string;
    public created_at: string;
    public display_name: string;
    public email: string;
    public email_verified: boolean;
    public logo: string;
    public name: string;
    public notifications: Object;
    public partnered: boolean;
    public twitter_connected: boolean;
    public type: string;
    public updated_at: string;

    constructor() {}

    deserialize(input: any) {
        this._id = input._id;
        this.bio = input.bio;
        this.created_at = input.created_at;
        this.display_name = input.display_name;
        this.email = input.email;
        this.email_verified = input.email_verified;
        this.logo = input.logo;
        this.name = input.name;
        this.notifications = input.notifications;
        this.partnered = input.partnered;
        this.twitter_connected = input.twitter_connected;
        this.type = input.type;
        this.updated_at = input.updated_at;

        return this;
    }
}

An alternative approach using Object.assign:

export class UserDetails implements Serializable<UserDetails>{

    constructor() {}

    deserialize(input: any) {
        Object.assign(this, input);

        return this;
    }
}

I am now faced with creating a new class that will have approximately 70 properties... Is this the most efficient method?


On Second Thought... Or should I consider a combination of both approaches for enhanced intellisense assistance?

export class UserDetails implements Serializable<UserDetails>{
    public _id: number;
    public bio: string;
    public created_at: string;
    public display_name: string;
    public email: string;
    public email_verified: boolean;
    public logo: string;
    public name: string;
    public notifications: Object;
    public partnered: boolean;
    public twitter_connected: boolean;
    public type: string;
    public updated_at: string;

    constructor() {}

    deserialize(input: any) {
        Object.assign(this, input);

        return this;
    }
}

Answer №1

In my perspective, implementing public class level fields could offer various advantages:

  1. It enhances intellisense functionality.
  2. An error should be raised when using any non-declared field (even if no field is declared). It's worth noting that utilizing Object.assign can introduce non-declared fields to the object.

For demonstration, check out this (fiddle link):

class Person {
  firstName;
  lastName;

  deserialize(input: any) {
    Object.assign(this, input);
    return this;
  }
}

let p = new Person();
p.deserialize({firstName:"John", lastName:"Doe", sex:"M"});

console.log(p);     //<-- outputs: Person { firstName: 'John', lastName: 'Doe', sex: 'M' }
console.log(p.sex); //<-- it displays 'M' in the console on JSFiddle.

Please note that even though the property sex is added to p, attempting to access it directly like in the second console.log should ideally trigger a compilation error, as shown below:

TSError: ⨯ Unable to compile TypeScript

nodesrc\test.ts (13,15): Property 'sex' does not exist on type 'Person'. (2339) ...

Therefore, if you prefer maintaining type-safety, declaring the fields upfront can be quite beneficial.

I hope this explanation proves useful.

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

Discovering JSON array keys in an Android environment

{ "204": { "host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/02\/0\/0\/A\/Content\/", "timestamp": 1385909880, "cover": ["17\/Pg017.png", ...

Having trouble getting dynamic values to render properly in Ionic select? Find a solution in Ionic 4

Encountering an issue with Ionic 4 and ion-select. The problem arises when attempting to bind data, specifically when preselecting data. In this scenario, the ion-select element fails to render properly. <ion-item class="transparent"> ...

What is the reason for a high-order generic function to eliminate falsy types from the argument list of the returned function?

Consider this example of a unique Decorator Factory Builder - a builder that constructs Decorator Factories to define metadata for forms: interface FormFieldOptions { name?: string; label?: string; format?: string; } type FormProperties = Record< ...

Capturing a center mouse click event in a directive for Angular 6

I created a unique custom directive where I aim to capture middle mouse button click events. Initially, I thought it would be a straightforward process by setting the normal click event and working from there. However, I noticed that it only triggers when ...

Utilizing Angular HTTP Interceptor to Show Loading Spinner Across Multiple Modules

My goal is to utilize the ng4-loading-spinner spinner when making HTTP calls to my API. I referred to the examples provided in the following resources: Angular Guide on Intercepting HTTP Requests/Responses Stack Overflow Post on Using HttpClient Interce ...

Utilize Express JS to send a JSON-formatted string in the HTTP response

How can I send a JSON string in an HTTP response using express JS? I'm attempting to do so but encountering errors. Could you please point out what mistake I might be making? msg = '{"foo": "bar"}'; msgJSON = JSON.parse(msg); res.status(200 ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

Converting an array into JSON format in JavaScript without duplicate curly braces

Having two parallel mysql queries in node js is meant to retrieve data more efficiently. The following javascript code reads from a mysql database and stores the results in a javascript object: async.parallel({ aaChannelsCount: function(cb) { /* G ...

Delaying navigation to the next URL until a distinct category name is identified

Within this section of JSP code, I am implementing JavaScript and AJAX to validate the uniqueness of a category name. When the submit button is pressed for the first time, it prompts the user to enter a category name. Subsequently, an AJAX call is made to ...

Tips for monitoring dispatch in fetch/middleware functions

Just testing a basic webpage <template> <HomeTemplate /> </template> <script lang="ts"> import Vue from 'vue' export default Vue.extend({ async fetch(context) { // or middleware(context) await context.store.disp ...

methods for translating a string from Json format to a regular string in python

After receiving a string in JSON format, I am working with it as a str type. The input looks like this: '{"name":"Jason", "age":"10"}' My goal is to convert it into a more conventional string output, structured like this: Jason 10 ...

Having issues resolving 'fs' or 'path' in Edge-js and Angular projects

I'm currently working on an Electron Angular application that utilizes electron-edge-js to seamlessly transition between Angular and C# code without the need for a separate server. Everything seems to be running smoothly until I actually try to call e ...

Guide to passing return value to CanDeactivate Guard post closing the mat-dialog in Angular Material Dialog

I have implemented a CanDeactivate Guard to detect unsaved changes in a form. When changes are detected, a confirmation dialog is displayed before allowing the user to leave the page. The Boolean value returned depends on the action taken in the dialog. C ...

Retrieve data from a local JSON file and showcase it in a list within a Next.js project. The error "Property 'data' does not exist on type String

Having trouble displaying the names of crates (which are filled with records/albums) from a local JSON file. The names aren't showing up and I'm wondering if I should be using params or if perhaps not stringifying the JSON would help. Visual Stud ...

Having trouble getting the Bootstrap toggle checkbox to function properly within Angular 2 components?

Working on an Angular 2 project with Bootstrap, I recently tried to integrate a bootstrap-toggle checkbox into the UI. Despite following the instructions from this site, the checkbox was displayed as a normal checkbox instead of toggled. The Index.html cod ...

get a collection of chosen files in angular 7 and save them to

Greetings, I am currently working on a project and encountering an issue. I need to download multiple selected files from a list, but despite my efforts in searching for a solution, I have been unable to find one. While I can successfully download single f ...

What is the best way to skip rows that throw errors in Redshift/Postgres? (Dealing with invalid JSON in json_extract_path_text)

Struggling with running a query in Redshift where I'm utilizing json_extract_path_text. Unfortunately, some JSON entries within the database column are invalid. The Issue: Whenever the query encounters an invalid JSON value, it halts and throws a "JS ...

The prefetch feature in typeahead is malfunctioning

I've been searching high and low for a solution, but I'm still coming up empty-handed. It seems like I must be making some mistake, but pinpointing exactly what it is remains elusive. Take a look at my typeahead code: $('.zoek').typeah ...

Detecting property changes in Angular 2: A step-by-step guide

I've created a basic class structure like so: export class MessagesPage { @ViewChild(Content) content: Content; public message = ''; public messages = []; public state = 'general'; } Can I implement a way wit ...

Instructions on how to incorporate a JSON file using a node HTTP server response (without the use of express)

I recently configured my first node HTTP server and I am currently working on retrieving response data from a JSON file in my application. Everything is functioning properly when I define a JSON object directly within the server.js file. data = "{&qu ...