2

Well basically my problem boils down to the fact that I can't have property with the same name I used for a getter or setter. This issue has more details: Duplicate declaration TypeScript Getter Setter.

So in order to avoid it I create my class in the following way (Here I show just one 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 problem with this is that the server expects the field's name to be phone_model, not _phone_model. I understand I could give my getters and setters names like Phone_model and then rename the private field to phone_modelbut...it would be against the conventions.

What would be the right way to handle this?

GoBear
  • 518
  • 1
  • 5
  • 19
  • How do you communicate with your server? through json? if you use reflection to dynamically get the property names, just strip of any leading underscores. if you don't do things dynamically just can just send the names you want anyway. – jcuypers Apr 07 '19 at 11:29
  • No, I don't use reflection. `RFilter` is the object I use in my post method. That's, as you see, it takes `task` as a parameter, then "strips" a few fields out of it (`phone_modle` is one of them) and then I use this `RFileter` object in my `post` request. But the server expects a `json` with names without the "_" prefix. So you suggest that I should just trim it somehow? – GoBear Apr 07 '19 at 11:39
  • Well nobody stops you from sending custom JSON '{ "phone_model" : getter_value }'. – jcuypers Apr 07 '19 at 12:37
  • Possible duplicate of [JSON stringify ES6 class property with getter/setter](https://stackoverflow.com/questions/42107492/json-stringify-es6-class-property-with-getter-setter) – Heretic Monkey Apr 08 '19 at 14:19

1 Answers1

0

So I did some checking and the following should bypass the manual JSON (I had the idea, but the nice code I have found on SO)

Add this on the top of your class (original code: 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[];

after that you can use

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));
jcuypers
  • 1,774
  • 2
  • 14
  • 23