這兩個功能的相似之處在於它們都是不可分配的。
能具體解釋一下嗎?
在這篇文章中,我將分享它們之間的差異。
在這種情況下,hisName 是一個不能重新分配的變數。
const hisName = 'Michael Scofield' hisName = 'Lincoln Burrows' // → ❌ Cannot assign to 'hisName' because it is a constant.
但是,您可以重新分配財產。
const hisFamily = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // → ⭕️ hisFamily = { mother: 'Christina Rose Scofield' } // → ❌ Cannot assign to 'hisFamily' because it is a constant.
例如,如果你嘗試用readonly給brother賦值,就會發生編譯錯誤。
let hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // → ❌ Cannot assign to 'brother' because it is a read-only property.
另一方面,允許對變數本身進行賦值。
let hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily = { brother: '' } // → ⭕️
const 使變數本身不可分配,而 readonly 使屬性不可分配。
透過組合 const 和 readonly,您可以建立一個對象,其中變數本身和對象的屬性都是不可變的。
const hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // ❌ Cannot assign to 'brother' because it is a read-only property. hisFamily = { brother: '' } // ❌ Cannot assign to 'hisFamily' because it is a constant.
快樂編碼☀️
以上是Type Script 中 readonly 和 const 的差別的詳細內容。更多資訊請關注PHP中文網其他相關文章!