Typescript:当只有一个属性更改时,是否使用类使用的接口属性的SET



我有一个接口(类似于数据库结构(,如下所示:

export interface Body {
health: number;
height: number;
hairlength: number;
}

以及以下的类别

export class Person {
private _body: Body;
private _name: string;
private _age: number;
constructor()....

get body(): Body {
return this._body
}
}

当只有一个属性从类外更改时,是否有方法在类内的主体接口上使用get/set,例如:

set body.hairlength(n: number) {
// Do some stuff
}

因此理发师可以使用:

static performHairCut(p: Person) {
p.body.hairlength -= 10
}

有了这个想法,我想把重复更新的属性与"偶尔"更新的属性分开

您可以返回包含getter/setter的对象,而不是直接返回Body对象,例如:

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
}
}
}
}

但是,我不推荐这种方法。在我看来,像这样的代码是模糊的,使用更大的接口(尤其是如果它们包含嵌套结构(会很快变得混乱。您应该查看ES6代理。

最新更新