首頁  >  文章  >  web前端  >  在 TypeScript 中使用 readonly 時的注意事項

在 TypeScript 中使用 readonly 時的注意事項

WBOY
WBOY原創
2024-08-11 06:02:01160瀏覽

Cautions When Using readonly in TypeScript

只讀屬性的基礎

在 Type Script 中,您可以將物件的屬性設為唯讀。

const person: { readonly name: string  } = { name: 'Mike' }

person.name = 21;
// → Cannot assign to 'name' because it is a read-only property.

⚠️① readonly 僅在編譯時

在編譯後的 JavaScript 程式碼中,只讀聲明被刪除,因此在執行時不會被偵測為錯誤。

⚠️② readonly 不是遞歸。

const person: {
  readonly name: string;
  readonly academicBackground: {
    primarySchool: string
  }
} = {
  name: 'Mike',
  academicBackground: {
    primarySchool: 'School A'
  }
}

person.academicBackground.primarySchool = 'School B'
// You can change `person.academicBackground.primarySchool`

如果你想將其設為唯讀,你還需要將 readonly 設為 PrimarySchool。

const person: {
  readonly name: string;
  readonly academicBackground: {
    readonly primarySchool: string
  }
} = {
  name: 'Mike',
  academicBackground: {
    primarySchool: 'School A'
  }
}

person.academicBackground.primarySchool = 'School B'
// → Cannot assign to 'primarySchool' because it is a read-only property.

只讀

當屬性數量增加時,為每個屬性添加 readonly 會變得很麻煩,並且會增加程式碼量。
您可以使用 Readonly 進行重構。

const obj: {
  readonly a : string;
  readonly b: string;
  readonly c: string;
  readonly d: string;
} = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
}

// ↓

const obj: Readonly<{
  a : string;
  b: string;
  c: string;
  d: string;
}> = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
}

快樂編碼☀️

以上是在 TypeScript 中使用 readonly 時的注意事項的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:雷迪斯下一篇:雷迪斯