예제
클래스 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)
에러내용

'TypeScript' 카테고리의 다른 글
| [타입스크립트] 인터페이스란? (인터페이스와 타입의 차이점) (0) | 2022.11.15 |
|---|---|
| [타입스크립트] 타입의 종류와 인터페이스 (0) | 2022.11.15 |
| [타입스크립트] 클래스 (0) | 2022.11.14 |
| [타입스크립트] 다형성(polymorphism)과 제네릭(generic) (0) | 2022.11.03 |
| [타입스크립트] 오버로딩(overloading)이란? (0) | 2022.11.03 |
댓글