一个只读属性之外的属性,但是对于类成员是可读写的属性
问题描述:
我希望在我的类中有一个属性,它是可读的,但不能由该类的外部代码直接修改。基本上,相当于从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;
什么是实现这一目标的正确方法是什么?
答
你可以做这样的事情:
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.
这几乎工作,但问题是,它失去了输入信息......也就是说,我不能ax'通过''到uniformMatrix4fv',因为打字稿编译器将其视为'ReadonlyTypedArray'而不是'Float32Array' –
nicebyte
@nicebyte但是类型化数组'Uint8Array'可以被突变。如果一个函数需要一个“Float32Array”类型的参数,那么它可以改变它。 – Paleo