这两个功能的相似之处在于它们都是不可分配的。
能具体解释一下吗?
在这篇文章中,我将分享它们之间的区别。
在这种情况下,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中文网其他相关文章!