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

nic*_*yte 8 typescript

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

写下这些内容:

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

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

let a = new test();
a.x()[0] = 1;
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*eer 18

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

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

    get x() {
        return this.x_;
    }
}
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)


Pal*_*leo 4

你可以这样做:

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.
Run Code Online (Sandbox Code Playgroud)