TypeScript
[타입스크립트] readonly(읽기전용)
메이플 🍁
2022. 11. 15. 15:37
예제
클래스 Word의 프로퍼티가 public이므로 kimchi.def이 수정이 가능하다
type Words = {
[key:string]: string
}
class Dict {
private words: Words
constructor(){
this.words = {}
}
add(word:Word) {
if(this.words[word.term] === undefined) {
this.words[word.term] = word.def
}
}
def(term:string) {
return this.words[term]
}
delete(term:string) {
delete this.words[term]
}
}
class Word {
constructor(
public term: string,
public def: string
){}
}
const kimchi = new Word('kimchi', '한국의 음식')
console.log(kimchi)
/*
{
"term": "kimchi",
"def": "한국의 음식"
}
*/
kimchi.def = 'somethig else'
console.log(kimchi)
/*
{
"term": "kimchi",
"def": "somethig else"
}
*/
프로퍼티의 값을 보여주고는 싶지만 수정은 불가능하게 하고 싶다면 프로퍼티를 readonly(읽기전용)으로 만들어준다.
type Words = {
[key:string]: string
}
class Dict {
private words: Words
constructor(){
this.words = {}
}
add(word:Word) {
if(this.words[word.term] === undefined) {
this.words[word.term] = word.def
}
}
def(term:string) {
return this.words[term]
}
delete(term:string) {
delete this.words[term]
}
}
class Word {
constructor(
public readonly term: string,
public readonly def: string
){}
}
const kimchi = new Word('kimchi', '한국의 음식')
console.log(kimchi)
kimchi.def = 'somethig else' // 에러발생: 읽기전용 프로퍼티는 수정불가
console.log(kimchi)
에러내용
