Retrieve the visibility and data type of an object's property in Javascript or Typescript

Issue at hand:

I am currently facing a challenge in distinguishing between the private, public, and getter (get X()) properties within a TypeScript class.

Current Project Scenario:

Within my Angular project, I have implemented a model design pattern. For instance, a user model is structured as follows:

class UserModel extends BaseModel {
    private _id: number;

    get id() { return this._id; }
    set id( _id: number ) { this._id = _id; }
}

When transmitting these models to the backend, I utilize JSON.stringify() which results in an object representation like the following, assuming the user id is set to 13:

{
    _id: 13
}

My current objective revolves around modifying the toJSON() function within the UserModel. Rather than returning the private properties of the object, I aim to solely output the get X() variables. The anticipated outcome is as follows:

{
    id: 13
}

In an attempt to fulfill this requirement, I have developed a simple function designed to retrieve all properties of an object. However, the challenge lies in achieving a distinction between the private and getter properties exclusively.

abstract class BaseModel {
    public propsToObj() : {[key: string]: any} {
        let ret: any = {};

        for (var prop in this) {
            ret[prop] = this[prop];
        }

        return ret;
    }
}

The updated toJSON function is outlined as follows:

class UserModel extends BaseModel {
    private _id: number;

    get id() { return this._id; }
    set id( _id: number ) { this._id = _id; }

    toJSON() {
        return this.propsToObj();
    }
}

Consequently, the resultant JSON representation of the UserModel after stringification looks like:

{
    _id: 13,
    id: 13
}

To summarize, I am seeking guidance on how to determine the visibility and nature (getter or standard variable?) of properties within a class. Any insights on how I can achieve this goal would be greatly appreciated.

Answer №1

There seems to be an issue with your propsToObj() function - it is currently retrieving all properties instead of just getters. To fix this, you can modify it to only include properties with getter functions, like this:

abstract class BaseModel {
    public propsToObj() : {[key: string]: any} {
      let ret: any = {};

      for (const prop in this) {
        const descriptor = Object.getOwnPropertyDescriptor(this.constructor.prototype, prop);
        if (descriptor && typeof descriptor.get === 'function') {
            ret[prop] = this[prop];
        }
      }
        return ret;
    }
}

Object.getOwnPropertyDescriptor will help you determine if a property has a getter function, allowing you to filter out only the relevant properties. You can learn more about descriptors here.

Regarding your question about determining property visibility and type:

I need to know the visibility and type of properties on a class, how would I achieve this?

Unfortunately, it is not possible to retrieve the visibility of a property. However, you can determine the data type of a property using the typeof operator.

Example within the propsToObj() method:

public propsToObj() : {[key: string]: any} {
      let ret: any = {};

      for (const prop in this) {
        const descriptor = Object.getOwnPropertyDescriptor(this.constructor.prototype, prop);
        if (descriptor && typeof descriptor.get === 'function') {
            ret[prop] = this[prop];
            console.log(typeof ret[prop]); // This shows you how to determine the type of the property
        }
      }
        return ret;
    }

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

Trouble keeping HTML/Javascript/CSS Collapsible Menu closed after refreshing the page

My issue is that the collapsible menu I have created does not remain closed when the page is refreshed. Upon reloading the page, the collapsible menu is always fully expanded, even if it was collapsed before the refresh. This creates a problem as there is ...

Mongoose encounters an issue: MissingSchemaError is thrown because the Schema has not been registered for the model

Encountering a perplexing error that I can't seem to resolve. I HAVE NAMED THE REF EXACTLY AS THE MODEL: MissingSchemaError: Schema hasn't been registered for model "ParticipantStatus". Here are the models in question: ParticipantStatus model: c ...

The ajax function does not provide a response

Can you help me figure out why this JavaScript function keeps returning 'undefined'? I really need it to return either true or false. I've included my code below: function Ajax() { var XML; if(window.XMLHttpRequest) XML=new ...

Storing information in Firebase using React.js

When storing an object in Firebase, I expected the structure to be as shown in the image below. However, what I received was a generated running number as a key. This is the code I used to store the object in Firebase: var location = []; location.push({ ...

Having difficulty assigning a value to a specific element within an array

When a button labeled "update" is clicked in an array called admin, I would like to display a div. The goal is for the div to appear below the selected element only and not affect any others in the array. function Admin(props) { const [showMe, setShowMe ...

Issue encountered during the upgrade to Angular version 12: The specified root path is undefined and does not correspond to any file in the program

During the process of upgrading my Angular 11 app to version 12, I encountered an error after running ng update @angular/core@12 @angular/cli@12 and then executing yarn start. The error that appeared can be found here: [Error After Run Angular in version 1 ...

Troubleshooting Issue: Angular 6 - Authentication token interceptor not including headers

After experimenting with various approaches using Angular 6 for the past couple of days, I recently tried implementing a solution mentioned in this post: . Despite my efforts, the header in the requests still remains unset. import {Inject, Injectable} fro ...

The process of implementing web-based online diagramming software involves a strategic approach to designing and integrating various

I'm really interested in learning how web-based online diagramming software works. If anyone could provide guidance or point me to example resources, I would greatly appreciate it. Here are some of the web-based online tools that I have been explorin ...

Creating a real-time face generator for a three.js shape

Currently, I am developing webgl software for generating 3D models that heavily relies on dynamic geometry. During my work, I have encountered some unusual behavior which I have managed to isolate in a JSFiddle demo. It appears that any new faces added af ...

What is the appropriate Typescript return type to use for a $http request that only returns a successful response with no content?

I recently developed a Typescript service: class SettingsService implements ISettingsService { public info = {}; public backupInfo = {}; public userConfig = {}; public isLoaded = false; constructor( private $http: ng.IHttpSer ...

The functionality of the Wordpress editor is impaired when the parent element is set to display:none during rendering

My goal is to create a popup window with text fields and a wp_editor. The content is already rendered in the footer but only set to display none. I have made attempts at implementing this, however, they are not working perfectly. Each approach has its own ...

Display a list of records retrieved from a Firebase query using ngFor to iterate through each instance

I'm currently using firebase and angular to work on a billing list project. The list contains data showing information for a specific month, you can refer to the imagehttps://i.stack.imgur.com/ZR4BE.png While querying the list was smooth, I encounte ...

Struggling with displaying a PDF file from the local directory in a NextJS application

I've been facing trouble importing and displaying my resume, a local file, within a react component. The code import myResume from '../assets/pdfs/myResume.pdf' is resulting in the error: Error: Cannot find module '../assets/pdfs/myRes ...

Guidance on installing only TypeScript dependencies for building from package.json using npm, ensuring a leaner build without unnecessary 150MB of additional dependencies

Is there a way to optimize the dependency installation process for building, minimizing unnecessary packages and reducing the total download size by avoiding 150MB of excess files? This is more of a query rather than an immediate requirement Current depe ...

Access denied: Unable to rename directory '/usr/local/lib/node_modules/expo-cli' due to permission restrictions

After encountering an error that appeared to be related to permissions, I spent some time troubleshooting and finally found a solution. I wanted to share it here in case it can help others facing the same issue. If anyone has alternative solutions, please ...

What is the best way to retrieve information from multiple pages of my REST API?

Recently, I integrated a search engine into my application and now I need to gather all the data available for a particular resource, such as all the posts made by a user. The response I receive from my API looks something like this: { "count": 2, ...

Utilizing jQuery to convert object properties into a table

Here is the table structure I am working with: <table> <thead> <tr> <th>Loan Type</th> <th>Amount Borrowed</th> <th>Current Payment< ...

conceal the .card-body element if the children have the CSS property "display:none"

My challenge involves managing two collapsible cards on a webpage. I am looking for a solution where the .card-body will have its display set to none when there are no inner divs to show in the card upon clicking a letter in the pagination. Otherwise, the ...

What is the best method to utilize a promise to delay the execution of a function until the data is received and stored

Currently, I am facing an issue with my API where the model variable is returning undefined before any data is populated in the return_array. I am unsure of how to implement promises or another method to ensure that the variable waits for data to be fille ...

What is the relationship between Typescript references, builds, and Docker?

I am facing a dilemma with my projectA which utilizes a common package that is also needed by my other Nodejs services. I am unsure of the best approach to package this in a Docker file. Ideally, running tsc build would compile both the project and the dep ...