0

i.e. if I have an object Person which looks like

class PersonClass implements Person {
  private _name : string;
  private _age : number;
  get name() : string {return this._name}
  get age() : number (return this._age)
  constructor(name : string, age : number) {
     this._name = name;
     this._age = age;
  }
 }

And I have interface with the public properties:

interface Person {
    name : string;
    age : string;
}

And what I need to do is get an object representation of the person which reflects the Person interface, and so looks like

{ name: John, age: 23}

Is there a way to do that? I tried casting ( person as Person } and JSON.stringify and object assign and I seem to end up with object that contains the private data _name and _age but not the interface members name and `age'

GGizmos
  • 3,443
  • 4
  • 27
  • 72
  • So you're looking for a new object which *only* contains the properties of the `Person` interface? – Naylor Aug 06 '21 at 17:23
  • This is strongly related to https://stackoverflow.com/questions/34517538/setting-an-es6-class-getter-to-enumerable. Judging by the answers in there, this is actually pretty tricky to make work. Have you thought about just a `toPlainObject` method instead? https://tsplay.dev/wgLQ4N – Alex Wayne Aug 06 '21 at 17:29

1 Answers1

0

It seems like what I want to do isn't straightforward, so I ended up using an approach which saves all the state variables in a private object that implements the interface, and when then when I want to get access to the data, I call a function which returns either a clone or the original dataobject.

something like:

interface Person {
    name : string;
    age : string;
}

class PersonClass implements Person {
   data : <Person>{} = {}
   constructor(name : string, age : number) {
       this.data.name = name;
       this.data.age = age;
   }
   get name() : string {return data.name}
   get age() : number {return data.age}
   get dataObject : return this.data;
}

Not perfect of course, because private can data can be manipulated from outside the class via the .dataObject, but if dataObject returns a deep copy of the data, then encapsulation can be maintained. A little extra work, but it makes retrieving data reading from a class and writing to the backend a little easier.

GGizmos
  • 3,443
  • 4
  • 27
  • 72