Home > Web Front-end > JS Tutorial > body text

The difference between readonly and const in Type Script

王林
Release: 2024-08-22 18:58:03
Original
166 people have browsed it

The difference between readonly and const in Type Script

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.

const prevents reassignment to a variable.

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.
Copy after login

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.
Copy after login

readonly prevents reassignment to a property.

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.
Copy after login

On the other hand, assigning to the variable itself is allowed.

let hisFamily: { readonly brother: string } = {
  brother: 'Lincoln Burrows'
}

hisFamily = {
  brother: ''
}
// → ⭕️
Copy after login

Conclusion

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.
Copy after login

Happy Coding☀️

The above is the detailed content of The difference between readonly and const in Type Script. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!