Reputation: 38
I have an interface (which resembles the database structure) as such:
export interface Body {
health: number;
height: number;
hairlength: number;
}
and a class as following
export class Person {
private _body: Body;
private _name: string;
private _age: number;
constructor()....
get body(): Body {
return this._body
}
}
is there a way to use get/set on the body interface inside the class when only one property is changed from outside the class, e.g.:
set body.hairlength(n: number) {
// Do some stuff
}
so a haircutter could use:
static performHairCut(p: Person) {
p.body.hairlength -= 10
}
With this idea I want to seperate repeatedly updating properties from "occasional" ones
Upvotes: 0
Views: 462
Reputation: 374
Instead of returning Body
object directly you can return object containing getters/setters like:
export interface Body {
health: number;
height: number;
hairlength: number;
}
export class Person {
private _body!: Body;
constructor() { }
get body(): Body {
const that = this;
return {
get health() {
return that._body.health;
},
set health(newValue: number) {
that.body.health = newValue
},
get height() {
return that._body.height;
},
set height(newValue: number) {
that.body.height = newValue
},
get hairlength() {
return that._body.hairlength;
},
set hairlength(newValue: number) {
that.body.hairlength = newValue
}
}
}
}
However, I don't recommend this approach. In my opinion code like this is obscure and can get messy very quickly with bigger interfaces (especially if they contain nested structures). You should check out ES6 proxies.
Upvotes: 1