FrontEnd :-)

Namad TS - 4. Classes And Interfaces ① 본문

TypeScript

Namad TS - 4. Classes And Interfaces ①

code10 2023. 2. 25. 14:28

4.0 Classes

//추상 클래스는 오직 다른 클래스가 상속받을 수 있는 클래스
//추상 클래스의 인스턴스를 만들 수 없음. new User 불가
//추상 메소드를 만들려면, 메소드를 클래스 안에서 구현해야 함.

abstract class User {
    constructor(
        private firstName: string,
        protected lastName: string,
        public nickname: string
    ){}
    abstract getLastName(): void
    
    getFullName(){
        return `${this.firstName} ${this.lastName}`
    }
}

class Player extends User {
	getLastName(){
    	console.log(this.lastName);
    }
}

const gwen = new Player("gwen", "lee", "그웬");

gwen.getFullName();

접근 가능한 위치

구분 선언한 클래스 내 상속받은 클래스 내  인스턴스
private O X X
protected O O X
public O O O

4.1 Recap

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){
        if(this.words[term]){
            delete 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");

Update

//단어 정의 수정
    updateDef(word: Word) {
        if (this.words[word.term]) {
            this.words[word.term] = word.def;
        }
    }
//단어 이름 수정
    updateTerm(oldTerm: string, newTerm: string) {
        if (this.words.hasOwnProperty(oldTerm)) {
            this.words[newTerm] = this.words[oldTerm];
            delete this.words[oldTerm];
        }
    }

기타

//사전에 저장된 단어 개수
    size() {
        return Object.keys(this.words).length;
    }
//사전 전체 출력
    all(){
        for(let [key, value] of Object.entries(this.words)){
            console.log(`${key}: ${value}`)
        }
    }

단어 정의 여러 개(문자열 배열) 가능하게, 정의 추가/수정/삭제

type Words = {
    [key:string]: (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){
        if(this.words[term]){
            delete this.words[term]
        }
    }
    //단어 정의 수정
    update(word: Word) {
        if (this.words[word.term]) {
            this.words[word.term] = word.def;
        }
    }
    //단어 이름 수정
    updateTerm(oldTerm: string, newTerm: string) {
        if (this.words.hasOwnProperty(oldTerm)) {
            this.words[newTerm] = this.words[oldTerm];
            delete this.words[oldTerm];
        }
    }

    //사전에 저장된 단어 개수
    size() {
        return Object.keys(this.words).length;
    }
    //사전 전체 출력
    all(){
        for(let [key, value] of Object.entries(this.words)){
            console.log(`${key}: ${value}`)
        }
    }
}

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

    //단어 정의 추가
    addDef(newDef: string) {
        if(typeof this.def === 'string'){
            this.def = [this.def, newDef]
        } else {
            this.def = [...this.def, newDef];
        }
    }
    //단어 기존 정의 <=> 새 정의 수정
    updateDef(oldDef: string, newDef: string){
        console.log("update", this.def, oldDef);
        if(typeof this.def === 'string'){
            if(oldDef === this.def) {
                this.def = newDef
            }
        } else {
            this.def = this.def.filter(v => v !== oldDef);
            console.log("filter", this.def);
            this.def.push(newDef);
            console.log("push", this.def);
        }
    }
    //단어 정의 삭제
    deleteDef(oldDef: string){
        if(typeof this.def !== 'string'){
            this.def = this.def.filter(v => v !=oldDef);
            // 정의 하나인 경우 [] => "" 바꿔주기
            if(kimchi.def.length === 1){
                this.def = this.def.toString();
            }
        }
    }
}

const kimchi = new Word("kimchi", "한국의 음식");
const galbi = new Word("갈비", "고기")
const dict = new Dict();

dict.add(kimchi);
dict.add(galbi);
dict.def("kimchi");

console.log 에서

kimchi.addDef("한국꺼!"); //kimchi.def = ["한국의 음식", "한국꺼!"]

kimchi.updateDef("한국의 음식", "Korean traditional food"); //kimchi.def = ["한국꺼!", "Korean traditional food"] 

 

몇 가지는 커뮤니티 게시판 댓글 참고했고, 몇 가지 더 추가함.

계속 생각할 게 생긴다,, 여기서 일단 마무리!

Comments