포시코딩

[TypeScript][노마드코더] #4 CLASSES AND INTERFACES(2) 본문

JavaScript

[TypeScript][노마드코더] #4 CLASSES AND INTERFACES(2)

포시 2023. 1. 22. 19:46
728x90

Class 심화

 

Constructor에서 직접 초기화 되지 않는 property 만들기

type Words = {
    [key: string]: string
}

class Dict {
    private words: Words  // Error!
}

위 코드는 에러가 발생한다. 

words는 initializer가 없고 Constructor에서 정의된 sign이 아니라는 에러인데

Constuctor에 포함시켜주지 않다보니 발생하는걸 볼 수 있다.

 

type Words = {
    [key: string]: string
}

class Dict {
    private words: Words
    constructor() {
        this.words = {}
    }
}

하지만 이렇게 작성할 경우 에러가 사라지는걸 볼 수 있다.

 

예제

type Words = {
    [key: string]: string
}

// property가 constructor부터 바로 초기화되지 않는 경우
class Dict {
    private words: Words
    constructor() {
        this.words = {}  // 수동으로 초기화
    }
    add(word: Word) {  
        // 클래스를 타입처럼 사용한 경우. 
        // 파라미터가 이 클래스의 인스턴스이길 원할 때 이렇게 사용할 수 있다. 
        // 추후 interface가 이런 사용법을 대체할거임
        if (this.words[word.term] === undefined) {  // 아직 사전에 존재하지 않을 때
            this.words[word.term] = word.def;
        }
    }
    def(term: string) {
        return this.words[term];
    }
}

class Word {
    constructor (
        public term: string, 
        public def: string
    ) {}
}

const kimchi = new Word('kimchi', '한국의 음식');

const dict = new Dict();

dict.add(kimchi);
dict.def('kimchi');

 

728x90