2017-11-25 169 views
1

我有這樣的代碼段在打字稿:ReadonlyArray在TypeScript中繼承了哪些類?

const arr: ReadonlyArray<string> = [ 
    "123", 
    "234" 
]; 

arr.push("345"); 

TS編譯器顯示了一個錯誤:Property 'push' does not exist on type 'ReadonlyArray<string>'。當然很顯然,我不能改變/改變這個數組,但問題是 - 什麼是ReadonlyArray的基類?它是否繼承了標準Array類?

+0

這是隻讀 - 你不能推上新的項目。那麼它將是可寫的。 –

+0

很明顯,這個數組是隻讀的,但我的問題是要弄清楚 - ReadonlyArray是如何實現的,它是從哪個基類派生出來的 –

+0

查看回答:)鏈接到裏面的源代碼 –

回答

2

https://www.typescriptlang.org/docs/handbook/interfaces.html 指出

TypeScript comes with a ReadonlyArray<T> type that is the same as Array<T> with all mutating methods removed, so you can make sure you don’t change your arrays after creation

如果你想要光源,頭部到

https://github.com/Microsoft/TypeScript/blob/master/src/lib/es5.d.ts#L978

(其定義爲線978在目前的版本)。

+0

這是一個相當普遍的答案'TypeScript來使用與Array 相同的ReadonlyArray 類型,並刪除所有變異方法。 那麼這是否意味着他們做了類似於: 'ReadonlyArray.prototype.push = null'? –

+0

很酷,謝謝! 這就是我正在尋找的。 –