”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在 TypeScript 中使用 readonly 时的注意事项

在 TypeScript 中使用 readonly 时的注意事项

发布于2024-08-21
浏览:101

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: 'a',
  b: 'b',
  c: 'c',
  d: 'd'
}

快乐编码☀️

版本声明 本文转载于:https://dev.to/noah-00/cautions-when-using-readonly-in-typescript-22d7?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3