These two features are similar in that they are both non-assignable.
Can you explain exactly it?
In this article, I will share the differences between them.
In this case, hisName is a variable that cannot be reassigned.
const hisName = 'Michael Scofield' hisName = 'Lincoln Burrows' // → ❌ Cannot assign to 'hisName' because it is a constant.
However, you can reassign to property.
const hisFamily = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // → ⭕️ hisFamily = { mother: 'Christina Rose Scofield' } // → ❌ Cannot assign to 'hisFamily' because it is a constant.
For example, if you try to assign a value to brother with readonly, a compilation error will occur.
let hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily.brother = '' // → ❌ Cannot assign to 'brother' because it is a read-only property.
On the other hand, assigning to the variable itself is allowed.
let hisFamily: { readonly brother: string } = { brother: 'Lincoln Burrows' } hisFamily = { brother: '' } // → ⭕️
const makes the variable itself non-assignable, while readonly makes the property non-assignable.
By combining const and readonly, you can create an object where both the variable itself and the object's properties are immutable.
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.
Happy Coding☀️
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3