Suppose I have a class with internal private properties:
export class foo {
private bar_:string;
private baz_:number;
constructor() { }
I know that I can get the values from bar and baz by writing a getter for the variable.
get bar():string {
return this.bar_;
}
get baz():number {
return this.baz_;
}
This then allows me to access data using:
let A:foo = new foo();
console.log(foo.baz);
Is there a way to have a simple generic getter, so when working with a more structured class, I could access any field without needing to write an individual get.
console.log(A.field2);
The field2 is not a defined getter, but I would like to be able to do something like the following in the class:
export class foo {
private bar_:string;
private baz_:number;
private field2_:string;
constructor() { }
get X():any { // X here is some placeholder that could be used, which contains the field name being asked (bar_, baz_, etc.)
return this.X; // This would assume that a field is the same name as what was passed.
}
On the HTML or other area, I could access the value as A.bar_ which would allow me to protect the private variable, but get external access to it without the need to write a getter for each field. This could then be extended to more complex structures as well.