2016-11-17 80 views
2

我希望在我的類中有一個屬性,它是可讀的,但不能由該類的外部代碼直接修改。基本上,相當於從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; 

什麼是實現這一目標的正確方法是什麼?

回答

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. 
+0

這幾乎工作,但問題是,它失去了輸入信息......也就是說,我不能ax'通過''到uniformMatrix4fv',因爲打字稿編譯器將其視爲'ReadonlyTypedArray '而不是'Float32Array' – nicebyte

+0

@nicebyte但是類型化數組'Uint8Array'可以被突變。如果一個函數需要一個「Float32Array」類型的參數,那麼它可以改變它。 – Paleo