」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Type Script 中 readonly 和 const 的區別

Type Script 中 readonly 和 const 的區別

發佈於2024-11-05
瀏覽:290

The difference between readonly and const in Type Script

這兩個功能的相似之處在於它們都是不可分配的。

能具體解釋一下嗎?

在這篇文章中,我將分享它們之間的差異。

const 防止重新分配給變數。

在這種情況下,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 防止重新指派給屬性。

例如,如果嘗試用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.

快樂編碼☀️

版本聲明 本文轉載於:https://dev.to/noah-00/the-difference-between-readonly-and-const-in-type-script-3po3?1如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3