[TypeScript] 사전 클래스 만들어 보기

제론·2022년 7월 5일
1
post-thumbnail

노마드 타입스크립트 챌린지를 하면서
배웠던 내용을 정리한다.

타입스크립트를 통해 사전에 단어를 추가하고 수정하고 삭제하고 출력하는 클래스를 만들어 봤다.

// 빈 객체 type 정의
type Words = {
    [key: string]: string
}

class Dict {
    // 사전이 될 빈 객체 생성
    private dictionary: Words
    constructor() {
        this.dictionary = {}
    }
    // 타입으로 클래스 지정 가능 => 여기선 파라미터가 해당 클래스의 인스턴스가 됨
    add(words: Word) {
        // 사전에 단어가 이미 존재하는지 확인
        if(this.dictionary[words.term] === undefined) {
            // 객체 리터럴로 사전에 새로운 단어 등록
            this.dictionary[words.term] = words.def
        }
    }
    get(term: string) {
        return this.dictionary[term]
    }
    delete(term: string) {
        if(this.dictionary[term] !== undefined) {
            delete this.dictionary[term]
        }
    }
    update(term:string, def:string) {
        if(this.dictionary[term]) {
            this.dictionary[term] = def
        }
    }
    showAll() {
        console.log(Object.keys(this.dictionary ))
    }
    count() {
        const dicCount = Object.keys(this.dictionary).length
        return dicCount
    }
}

// 사전에 입력 받을 단어의 타입 정의
class Word {
    constructor(
        public term: string,
        public def: string
    ) {}
}

배운 것

  • 클래스에 대해서 좀 더 이해할 수 있었다. -> constructor로 초기화, 메서드 추가

  • 타입스크립트에서 객체 타입을 정의하는 방법을 알았다.
    [key: string]: string

  • 클래스를 타입으로 지정하는 방법을 배웠다.-> 위 예제에서 Word라는 클래스를 add 메서드의 인수로 지정

profile
Software Developer

0개의 댓글