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

Having trouble with PHP JSON response not functioning properly?

I'm currently working on an ajax update and I simply need a success or failure response to handle some front-end tasks. However, I am facing issues as it doesn't seem to be functioning properly. I'm fairly new to all of this. $('.delet ...

Unable to combine mui theme with emotion css prop

I recently made the switch from overwriting styles in my styles.css file with !important to using emotion css prop for implementing a dark theme in my web app. Below is the code snippet from App.tsx where I define my theme and utilize ThemeProvider: const ...

Leveraging AJAX for fetching data from a deeply nested JSON structure

My AJAX request is functioning properly: $.ajax ({ url: 'api.php', type: 'GET', data: {search_term: data}, dataType: 'JSON', success: function(data) { $('#div').html('<p>Consti ...

efficient ways to eliminate redundant JSON objects in Python

How can I remove objects with duplicate 'file_url' from a JSON file? { "0": { "file_url": "apple", "name": "apple.jpg" }, "1": { "file_url": "dog", "name": "dog.jpg" }, "2": { "file_url ...

Client-side condition handling in Angular 2

How can I change the icon image on a block/unblock button based on the user's active status? For example, showing an unlock image when the user is active and vice versa. Image https://i.stack.imgur.com/aM0ff.png Html <link href="../../font-aw ...

Learn how to successfully import a webp image into a React TypeScript project

I have looked everywhere for the answer, but I can't seem to find it When trying to import a *.webp image in typescript, you need to create a declaration file, like declaration.d.ts The declaration file should contain something similar to the foll ...

Parameters for constructing classes in TypeScript

I've been exploring different coding styles in TypeScript recently. When it comes to initializing an object from a class, what are the advantages and disadvantages of these two code styles in TypeScript? class Class3 { // members private rea ...

Angular is throwing a RangeError due to exceeding the maximum call stack size

Encountering a stackOverflow error in my Angular app. (see updates at the end) The main issue lies within my component structure, which consists of two components: the equipment component with equipment information and the socket component displaying conn ...

Parsing issue with JSON encoding in Perl due to a missing comma

My script in Perl is generating incorrect JSON output with missing commas between blocks: { "data": [{ "{#LOGFILEPATH}": "/tmp/QRZ2007.tcserverlogs", "{#LOGFILE}": "QRZ2007" } **missing comma** { "{#LOGFILE}": "ARZ2007", ...

What is the process of organizing information with http in Angular 2?

Currently, I am working through a heroes tutorial and have made progress with the code so far. You can view the code <a href="https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?preview" rel="nofollow noreferrer">here</a>. My next goal is to implement ...

Retrieve the initial key from an object in javascript

Though seemingly simple, I'm stuck on finding the solution: Within my jquery object (displayed in console.log): { id_ship: "1", id_company: "1", code: "DE", // other properties... } My goal is to extract the first key from th ...

Type-constrained generic key access for enhanced security

While attempting to create a versatile function that retrieves the value of a boolean property using a type-safe approach, I encountered an issue with the compiler not recognizing the type of my value. type KeyOfType<T, V> = keyof { [P in keyof T a ...

How can I construct a Query Builder expression in Laravel that involves selecting from 2 different tables?

I am struggling with translating this SQL query to a query builder syntax: select products.* from orders, json_table( orders.order_summary, "$.products[*]" columns( quantity int path "$.quantity", variant_id int path ...

Asynchronous jQuery operations using promises and finally functionality

I am attempting to interact with a REST api using jQuery's ajax feature. My goal is to return the Promise<Customer> object, but I am encountering an error stating that the property finally is missing. It used to work before, so I assume there h ...

Guide to incorporating Angular 2 code into your Rails application

As a beginner in Ruby on Rails, I have recently learned some CRUD functionalities with RoR. Additionally, I am just starting my journey with Angular 2 and currently learning the basics. I noticed that RoR has its own HTML template engine similar to Angula ...

The jQuery functions properly offline, but fails to load when connected to the

I am encountering an issue with the following script: <script type="text/javascript"> $.getJSON("http://api.twitter.com/1/statuses/user_timeline/koawatea.json?count=1&include_rts=1&callback=?", function(data) { $("#headertweet") ...

Tips for viewing the content of an authentication-required API in a browser

Currently, I am in the process of developing an Android project that requires accessing a specific github API. This particular API contains vital information regarding user repositories. Before diving into Android programming, I am eager to explore the c ...

Using next.js with GraphQL resulted in the following error: "Invariant Violation: Unable to locate the "client" in the context or passed in as an option..."

I've searched extensively online, but I can't find a solution to my problem. Here is the error message I'm encountering: Invariant Violation: Could not find "client" in the context or passed in as an option. Wrap the root component in an ...

passing JSON data using JavaScript or jQuery

I have a JSON snippet that I need to parse using JavaScript or jQuery and convert into variables: name and meetup. Can you help me with this? Below is the JSON code: { "MYID": 1, "module": [ { "name": "Manchester", ...

Having trouble with jQuery.cookie saving my JSON data

Being new to jQuery and JSON, I find this situation quite frustrating as it seems pretty straightforward but still doesn't work for me. My ASP.NET MVC website is using AJAX (via jQuery) to load data. Everything works fine until this point. I'm ...