[Typescript] Classes

Donghee Choi·2024년 6월 28일

typescript

목록 보기
1/2
  1. 파라미터들을 써주기만 하면 타입스크립트가 알아서 Constructor 함수를 만들어준다.
class Player {
	constructor(
    	private firstName:string,
        private lastName:string,
        public nickName:string
    ){}
}

const donghee = new Player('donghee', 'choi', 'dongdong')
  1. 추상클래스(Abstract Class)
  • 다른 클래스가 상속받을 수 있는 클래스
  • 이 클래스는 직접 새로운 인스턴스를 만들 수는 없다. ex) new User() (x)
  • 추상클래스에서 추상 메소드는 call signature로만 작성해야한다.
  • 추상 메소드는 추상 클래스를 상속받는 모든 것들이 구현을 해야하는 메소드
  • private은 추상 클래스를 상속받았을지라도 접근할 수 없다. (인스턴스 밖에서 접근 불가)
  • protected : 보호받길 원하지만 다른 자식 클래스에서는 사용하고 싶을때
abstract class User {
	constructor(
    	private firstName:string,
        private lastName:string,
        private nickName:string
    ){}
    abstract getNickName():void;
    getFullName() {
    	return `${this.firstName} ${this.lastName}`
    }
}

class Player extends User {
	getNickName() {
    }
}

const donghee = new Player('donghee', 'choi', 'dongdong');

donghee.getFullName();
  1. 사전 클래스 만들기
    해시맵으로 사전을 만들어보자.
    사전에 새 단어를 추가하고, 단어를 찾고, 단어를 삭제하는 메소드를 만들어보자.

아래 2개 클래스의 차이점은 다음과 같다.
Dict 클래스는 명시적으로 빈 객체로 초기화 한다.
Dict2 클래스는 생성자 파라미터를 선언함과 동시에 초기화한다.
사전 클래스에서는 Dict 클래스가 맞다.

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

class Dict2 {
  constructor(private words: Words) {}
}

사전 클래스 만들기

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];
  }
}

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

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

const dict = new Dict();

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

챌린지 코드

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;
    }
  }

  get(term: string) {
    return this.words[term];
  }

  delete(term: string) {
    delete this.words[term];
  }

  update(word:Word) {
    if(this.exists(word.term)) {
        this.words[word.term] = word.def
    }
  }

  showAll() {
    return this.words;
  }

  count() {
    return Object.entries(this.words).length;
  }

  upsert(word: Word) {
    if (this.words[word.term] === undefined) {
      this.add(word);
    } else {
      this.update(word)
    }
  }

  exists(term: string) {
    return Object.keys(this.words).find((key) => key === term) !== undefined;
  }

  bulkAdd(bulkWords: Word[]) {
    bulkWords.forEach((item) => {
      this.add(item);
    });
  }

  bulkDelete(terms: string[]) {
    Object.keys(this.words).forEach((key) => {
      if (terms.includes(key)) {
        this.delete(key);
      }
    });
  }
}

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

  update(def: string) {
    this.def = def;
  }
}

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

const dict = new Dict();

dict.add(kimchi);

console.log(dict.get('kimchi'))

//dict.delete('kimchi');


kimchi.update('한국의 맛있는 음식');
dict.update(kimchi)
console.log(dict.get('kimchi'))

console.log(dict.count())
const apple = new Word('apple', '사과');
const aa = new Word('kimchi','ㅁㅁ')
dict.upsert(apple)
dict.upsert(aa)
console.log(dict.exists('kimchi'))

dict.bulkAdd([{term:"김치", def:"대박이네~"} as Word, {term:"아파트", def:"비싸네~"} as Word])
dict.bulkDelete(['김치', '아파트'])
console.log(dict.showAll())

챌린지 코드 해설

type Word = {
  term:string;
  definition:string;
}

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

class Dict {
  private words: Words;
  constructor() {
    this.words = {};
  }
  add(term: string, definition: string) {
    if (!this.get(term)) {
      this.words[term] = definition;
    }
  }
  get(term: string) {
    return this.words[term];
  }
  delete(term: string) {
    delete this.words[term];
  }
  update(term: string, newDef: string) {
    if (this.get(term)) {
      this.words[term] = newDef;
    }
  }
  showAll() {
    let output = "\n--- Dictionary Content ---\n"
    Object.keys(this.words).forEach((term) =>
      output += `${term}: ${this.words[term]}\n`
    );
    output += "--- End of Dictionary ---\n"
    console.log(output);
  }
  count() {
    return Object.keys(this.words).length;
  }
  upsert(term:string, definition:string){
    if(this.get(term)){
      this.update(term, definition);
    } else {
      this.add(term, definition);
    }
  }
  exists(term:string){
    return this.get(term) ? true : false;
  }
  bulkAdd(words: Word[]){
    words.forEach(word => this.add(word.term, word.definition))
  }
  bulkDelete(terms: string[]){
    terms.forEach(term => this.delete(term));
  }
}

const dictionary = new Dict();

const KIMCHI = "김치"


// Add
dictionary.add(KIMCHI, "밋있는 한국 음식");
dictionary.showAll();

// Count
console.log(dictionary.count());

// Update
dictionary.update(KIMCHI, "밋있는 한국 음식!!!");
console.log(dictionary.get(KIMCHI));

// Delete
dictionary.delete(KIMCHI);
console.log(dictionary.count());

// Upsert
dictionary.upsert(KIMCHI, "밋있는 한국 음식!!!");
console.log(dictionary.get(KIMCHI))
dictionary.upsert(KIMCHI, "진짜 밋있는 한국 음식!!!");
console.log(dictionary.get(KIMCHI))

// Exists
console.log(dictionary.exists(KIMCHI))

// Bulk Add
dictionary.bulkAdd([{term:"A", definition:"B"}, {term:"X", definition:"Y"}]);
dictionary.showAll();

// Bulk Delete
dictionary.bulkDelete(["A", "X"])
dictionary.showAll();
profile
frontend, vuejs, react, docker, kubernetes

0개의 댓글