Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 在类外部为只读,但对类成员为读写的属性_Typescript - Fatal编程技术网

Typescript 在类外部为只读,但对类成员为读写的属性

Typescript 在类外部为只读,但对类成员为读写的属性,typescript,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; 实现这一目标的正确方法是什么?您

我希望在我的类中有一个可读的属性,但不能由类外部的代码直接修改。基本上,等效于从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.
接口只读类型Darray{
只读[索引:编号]:T
}
课堂测试{
private_x=新的Uint8Array([0,1,2]);
public get x():ReadonlyTypedArray{
把这个还给我;
}
}
设a=新测试();
a、 x[0]=1;//错误:赋值表达式的左侧不能是常量或只读属性。
a、 x=新的UINT8数组([0,1,2]);//错误:赋值表达式的左侧不能是常量或只读属性。

可以声明第二个私有属性
xValue
。它将包含该值,并且可以从内部进行编辑。公共属性
x
将只是一个getter(最好是
getX
方法以防止混淆)。

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

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

    get x() {
        return this.x_;
    }
}

这几乎可以工作,但问题是它会丢失类型信息。。。也就是说,我无法将
a.x
传递给
uniformMatrix4fv
,因为typescript编译器将其视为
ReadonlyTypedArray
而不是
Float32Array
@nicebyte,但是类型化数组
Uint8Array
可以进行变异。如果函数需要类型为
Float32Array
的参数,那么它可以对其进行变异。嘿,你能更新问题标题吗?这有点误导,因为它似乎只关注简单的类属性,而实际上您要问的是如何使数组属性项从类外部不可修改,因此更像是“着色实际属性类型”。
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.