一个在类外部是只读的属性,但对类成员进行读写

时间:2016-11-17 08:34:50

标签: typescript

我想在我的班级中拥有一个可读的属性,但不能通过类外部的代码直接修改。基本上,相当于从C ++中的方法返回const引用到成员。

沿着这些方向写一些东西:

class test {
    private readonly x_ = new Uint8Array([0, 1, 2]);
    public x() { return this.x_;}
}

不起作用,因为以下代码仍然编译:

let a = new test();
a.x()[0] = 1;

实现这一目标的正确方法是什么?

3 个答案:

答案 0 :(得分:1)

你可以这样做:

interface ReadonlyTypedArray<T> {
    readonly [index: number]: T
}

class test {
    private _x = new Uint8Array([0, 1, 2]);
    public get x(): ReadonlyTypedArray<number> {
        return this._x;
    }
}

let a = new test();
a.x[0] = 1; // Error: Left-hand side of assignment expression cannot be a constant or a read-only property.
a.x = new Uint8Array([0, 1, 2]); // Error: Left-hand side of assignment expression cannot be a constant or a read-only property.

答案 1 :(得分:1)

对于未来的读者,我们可以使用 getter 允许在类外阅读属性,但限制编辑。

class Test {
    private x_ = new Uint8Array([0, 1, 2]);

    get x() {
        return this.x_;
    }
}
let test = new Test();
console.log(test.x) //Can read
test.x = 1; //Error: Cannot assign to 'x' because it is a read-only property.

答案 2 :(得分:0)

可以声明第二个私有属性xValue。它包含值,并且可以从内部进行编辑。公共财产x只会是一种吸气剂(最好是getX方法,以免造成混淆)。

相关问题