2016-09-06 39 views
1

考慮下面的小片段:私人會員爲什麼可以通過方括號表示法訪問?

class BlueprintNode { 
    private metadata: number[] = []; 
} 

var node = new BlueprintNode(); 
node["metadata"].push("Access violation, rangers lead the way."); 

Demo on TypeScript Playground

怎麼來的打字稿編譯器允許通過使用方括號標記的訪問私有成員?它甚至可以正確地檢測給定屬性的類型。使用點符號,它會正確顯示編譯錯誤。

+1

我想這是因爲方括號表示法適用於任何對象,TypeScript想盡可能地接近JavaScript。我認爲試圖限制你使用方括號是沒有意義的,即使編譯器能夠檢查'node [「metadata」]'實際上是一個私有屬性,因爲你總是可以繞過這個檢查像'node [propName]'這樣的變量。 看看這個答案btw:http://stackoverflow.com/a/12713869/310726 – martin

回答

2

訪問時使用索引的編譯器將把這個對象是這樣的對象屬性:

interface BlueprintNode { 
    metadata: number[]; 
    [key: string]: any; 
} 

如果然後做:

let node: BlueprintNode; 
node["metadata"].push("Access violation, rangers lead the way."); 

你會得到相同的錯誤與您的代碼。

+0

我假設隱式公共索引簽名將有效地覆蓋成員保護在適用情況下,事實證明這是正確的在實踐中。 –