有没有办法在TypeScript中为属性设置私有的setter?
class Test
{
private _prop: string;
public get prop() : string
{
return this._prop;
}
private set prop(val: string)
{
//can put breakpoints here
this._prop = val;
}
}
编译器抱怨getter和setter的可见性不匹配。我知道我可以设置支持字段,但是当设置值时我不能设置断点。
我虽然使用接口来隐藏setter,但接口只能定义一个属性,而不是它是否在setter上有getter。
我在这里遗漏了什么吗?似乎没有任何理由不允许私人制定者,由此产生的JS无论如何都不会强制实施可见性,并且看起来比目前的替代方案更好。
我错过了什么吗?如果不是没有私人制定者的充分理由?
答案 0 :(得分:50)
TypeScript规范(8.4.3)说......
相同成员名称的访问者必须指定相同的辅助功能
所以你必须选择一个合适的替代方案。以下是两个选项:
你可以没有一个setter,这意味着只有Test
类能够设置属性。您可以在第this._prop =...
行上放置一个断点。
class Test
{
private _prop: string;
public get prop() : string
{
return this._prop;
}
doSomething() {
this._prop = 'I can set it!';
}
}
var test = new Test();
test._prop = 'I cannot!';
可能确保私人访问的理想方式会导致类似于"通知属性的更改"可以实现的模式是拥有一对私有的get / set属性访问器,以及一个单独的public get属性访问器。
您仍然需要谨慎对待后来直接调用支持字段的人。您可以在该领域发挥创意,尝试降低其可能性。
class Test
{
private _nameBackingField: string;
private get _name() : string
{
return this._nameBackingField;
}
private set _name(val: string)
{
this._nameBackingField = val;
// other actions... notify the property has changed etc
}
public get name(): string {
return this._name;
}
doSomething() {
this._name += 'Additional Stuff';
}
}
答案 1 :(得分:4)
我也希望我们可以有公共吸气者和私人制定者。在我们这样做之前,另一种处理方法是添加额外的私有getter和setter:
class Test {
_prop: string;
public get prop(): string {
return this._prop;
}
private get internalProp(): string {
return this.prop;
}
private set internalProp(value: string) {
this._prop = value;
}
private addToProp(valueToAdd: string): void {
this.internalProp += valueToAdd;
}
}