An issue arises with getters and setters in TypeScript due to a duplicate identifier error for 'phone_model'

Essentially, my issue revolves around the restriction of not being able to have a property with the same name as used for a getter or setter. For more detailed information on this problem, you can refer to: Duplicate declaration TypeScript Getter Setter.

To work around this limitation, I have structured my class in the following manner (provided here is just one of its private fields):

export class RFilter
{
    private _phone_model: string;

    constructor(task: Task)
    {
        this.phone_model = task.phone_model;
    }

    set phone_model(val: string)
    {
        this._phone_model = val;
    }

    get phone_model(): string
    {
        return this._phone_model;
    }

The challenge arises from the server expecting the field's name to be phone_model, not

_phone_model</code. While I could name my getters and setters differently, like <code>Phone_model
, and rename the private field accordingly to phone_model, it goes against convention.

What would be the most appropriate approach to address this issue?

Answer №1

After doing some research, I discovered a clever workaround for manually handling JSON by incorporating code found on SO.

To implement this solution, simply add the following snippet to the beginning of your class (original code source: Get properties of class in typescript / @nitzantomer):

public static getGetters(): string[] {
   return Reflect.ownKeys(this.prototype).filter(name => {
      return typeof Reflect.getOwnPropertyDescriptor(this.prototype, name)["get"] === "function";
 }) as string[];

Once this is done, you can utilize the code below:

let rFilter = new RFilter();
rFilter.phone_model = "flashy phone";

let obj = {};

for (getter of RFilter.getGetters()) {
   console.log(getter " - "+rFilter[getter]);
   obj[name] = settings[name];
}

console.log(JSON.stringify(obj));

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

Removing a targeted element from an array in Angular

After receiving a JSON array object in Angular using TypeScript, I am attempting to remove a specified object from it. However, my attempts at deletion have been unsuccessful. addCategorySub(categorySub: CategorySubModel, index: number) { categorySub.id ...

Tips for structuring TypeScript with MobX in a ReactJS project

I created a MobX store as shown below. I defined the types of actions in store.js import { action, observable } from 'mobx'; export class SignStore { @observable UserInformation: { email: ''; password: ''; ...

How to retrieve data from the resolve function in an Angular 2 component

How can I access the resolved data in an Angular 2 migrated component? I have an Angular JS app.config set up with routing that loads the necessary Angular 2 migrated component. .state('users.list', { url: '/users/list', templ ...

I am working in Angular 13 and attempting to dynamically assign attributes to an SVG HTML element by passing in values from variables declared in a TypeScript file

Within a specific HTML file of my Angular13 app, I'm aiming to dynamically bind a list of attributes and their values to an element using Angular's double-binding approach {{attribute value}}. This will allow me to display a series of social medi ...

VS Code fails to identify Typescript internal modules

I am currently facing issues with separating my TypeScript classes into distinct files using internal modules. Unfortunately, the main.ts file is not loading or recognizing the sub-modules. main.ts /// <reference path="Car.ts" /> module Vehicles { ...

When building websites, pages, or applications with React, how do you determine the best choice between JavaScript, TypeScript, or JavaScriptXML?

After completing my portfolio and an eCommerce website design using Figma, I started learning React and Tailwind with Vite. I'm comfortable with basic JavaScript but now I want to understand the differences between .js, .jsx, and .ts files when workin ...

best practices for filtering custom data returned from valuePreparefunction in ng2 smart table

Having an issue with the filter in ng2 smart table because I am returning custom data from the valueprepareFunction. This is my setup... columns: { id: { title: 'Id', type: 'string' }, surname: { title: 'surname', ty ...

The Angular Universal Starter is running smoothly on local environments, but encountering difficulties when attempting to launch on the

My current challenge involves running Angular Universal Starter on a Centos server. Executing build:ssr and serve:ssr locally works without any issues. After transferring the dist folder to the server, I updated nodejs, npm, and pm2 to their latest ver ...

When ng-test is executed in an Angular service, the function array.some is not found

After retrieving allUsers from the cache and initializing it, I then set the boolean value of specialUserExists based on a condition in allUsers using allUsers.some() (reference to the Array.prototype.some() method). service.ts @Injectable({ providedIn: ...

An issue occurred: Unable to access the 'login' property because of a TypeError

Setting up a login page and declaring an object in my login.ts file. public User: { login:"", senha:"", }; Utilizing [ngModel] to save values within the parameters of the object. <ion-item> <ion-label floating>Enter ...

Incorrect object being returned from Angular 2 HTTP request

For my data fetching from the server, I am using @angular/http get method. Below is the code snippet: private _currentPT: any; public phongtroDetailChange = new Subject(); layPhongtro(id: number): Promise<any> { return new Promise((resolve, reject) ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

Testing a function that utilizes Nitro's useStorage functionality involves creating mock data to simulate the storage behavior

I have developed a custom function for caching management, specifically for storing responses from API calls. export const cache = async (key: string, callback: Function) => { const cacheKey = `cache:${key}`; const data = await useStorage().get ...

What are the steps to set up ChartJS on a personal computer?

Currently, I am working on creating charts with ChartJS using the CDN version. However, I would like to have it installed directly on my website. After downloading ChartJS v4.1.1, I realized that it only contains typescript files. Since I cannot use TS fil ...

When trying to click the button in Navbar.jsx, I encounter an error when attempting to invoke the setShowCart(true) function

I've encountered an issue while trying to call the setShowCart(true) function in Navbar.jsx. I'm unsure of how to fix this. import React from 'react' import Link from 'next/link'; import {AiOutlineShopping} from 'react-ic ...

Implementing Boolean filtering on arrays in Angular

Greetings! As a beginner in Angular, I am currently exploring ways to sort an array generated using *ngFor. My goal is to utilize input checkboxes for filtering. I have added properties to the objects such as... PersonalInvestment: boolean; This property ...

Tips for building a dynamic view using Angular

I am working on a project where I need to dynamically generate multiple horizontal lines using data from a JSON file, similar to the example in the image below. https://i.sstatic.net/MthcU.png Here is my attempt: https://i.sstatic.net/EEy4k.png Component. ...

Querying Angular/Firestore for a collection document to extract a single field from each document and store them in an array

I am currently querying my collection of documents and attempting to extract only the phone numbers into an array. The goal is to store the phone numbers in an array for use by another function. While the Firebase documentation provides examples using co ...

What is the process for changing the value type of a function in an already existing record?

Trying to create a function that transforms the definitions of object functions into different, yet predictable, functions. For example: converter<{ foo: (n: number) => void, bar: (s: string) => void }>({ foo: fooFunction, bar: barFunc ...

Every time I attempt to use interpolation in Angular 11, the result ends up being displayed as plain text on

I'm a beginner in Angular and I recently attempted my first code following a tutorial. When running this code on a live server using port 5500, I encountered an issue with interpolation. <h1>{{title}}</h1> The result on the webpage displa ...