Type Script에서 읽기 전용과 const의 차이점

王林
풀어 주다: 2024-08-22 18:58:03
원래의
167명이 탐색했습니다.

The difference between readonly and const in Type Script

이 두 기능은 모두 할당할 수 없다는 점에서 유사합니다.

정확하게 설명해주실 수 있나요?

이 기사에서는 이들 간의 차이점을 공유하겠습니다.

const는 변수에 대한 재할당을 방지합니다.

이 경우 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에서 읽기 전용과 const의 차이점의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!