私人二传手打字稿? [英] Private setter typescript?

查看:82
本文介绍了私人二传手打字稿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在TypeScript中为属性设置私有设置器?

Is there a way to have a private setter for a property in TypeScript?

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的可见性不匹配.我知道我可以设置背景字段,但设置值时不能设置断点.

Compiler complains that visibility for getter and setter don't match. I know I can just set the backing field, but but then I can't set breakpoints when the value is set.

尽管我要使用接口来隐藏设置器,但是接口只能定义属性,而不能定义设置器上是否具有getter.

I though about using an interface to hide the setter, but interfaces can only define a property, not whether it has a getter on setter.

我在这里错过了什么吗?似乎没有任何理由不允许使用私有设置器,因此生成的JS无论如何都不会强制执行可见性,并且与当前的替代方法相比似乎更好.

Am I missing something here? There doesn't seem to be any reason to not allow private setters, the resulting JS doesn't enforce visibility anyway, and seems better that the current alternatives.

我错过了什么吗?如果没有的话,没有很好的理由不设私人二传手吗?

Am I missing something? If not is there a good reason for no private setters?

推荐答案

TypeScript规范(8.4.3)表示...

The TypeScript specification (8.4.3) says...

具有相同成员名称的访问者必须指定相同的可访问性

Accessors for the same member name must specify the same accessibility

因此,您必须选择一个合适的替代方案.这里有两个选项供您选择:

So you have to choose a suitable alternative. Here are two options for you:

您只能没有设置器,这意味着只有Test类才可以设置属性.您可以在this._prop =...行上放置一个断点.

You can just not have a setter, which means only the Test class is able to set the property. You can place a breakpoint on the line 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属性访问器.

Probably the ideal way to ensure private access results in something akin to a "notify property changed" pattern can be implemented is to have a pair of private get/set property accessors, and a separate public get property accessor.

您仍然需要对以后将直接呼叫添加到备用字段的某人保持谨慎.您可以在该领域内发挥创意,尝试并减少这种可能性.

You still need to be cautious about someone later adding a direct call to the backing field. You could get creative in that area to try and make it less likely.

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

这篇关于私人二传手打字稿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆