타입스크립트의 Class

유재헌·2023년 2월 8일
0

Typescript

목록 보기
7/8
//추상 클래스: 다른 클래스가 상속받을 수만 있는 클래스
abstract class User {
  constructor(
  	private firstName: string,
    protected lastName: string,
    public nickName: string
  ) {}
  //아래와 같이 추상클래스안에 추상메서드를 만들려면 내용을 구현하지 말고 
  //위처럼 메서드의 call signature만 작성해야 한다.
  //대신 상속받는 클래스에서 내용을 구현해줘야 한다.
  abstract getNickName(): void
  
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

//Player클래스가 User클래스를 상속한다.
//
class Player extends User {
  
}

const timothy = new Player("timothy", "kim", "tim");

timothy.lastName; // -> ❌ protected라서 접근 불가능
timothy.nickName // -> ⭕ public이라서 접근 가능

timothy.getFullName();// -> ⭕ call signature로 메소드를 구현해서 접근가능
접근가능여부선언한 클래스 내상속받은 클래스 내인스턴스
private
protected
public

예시

/** ↓ Words타입이 string만을 프로퍼티로 가지는 오브젝트라는 것.
제한된 양의 property 혹은 key를 가지는 타입을 정의해주는 방법이다.
객체의 property에 대해 모르지만 타입만을 알 때 유용하다.
**/
type Words = {
  [whatever: string]: string
}

/*
let dict: Words = {
	"potato": "food"
}
둘 다 string이어야 한다. number라면 number이어야 한다.
*/

class Dict {
  private words: Words
  constructor() {
    this.word = {}
  }//수동으로 초기화
  //단어를 추가하기 위한 메소드
  //클래스를 타입처럼 사용
  //파라미터(word)가 클래스(Word)의 인스턴스이길 원할 때 이렇게 작성.
  add(word: Word) {
    if(this.words[word.term] === undefined) {
      this.words[word.term] = word.def
    }
  }
}

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

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

const dict = new Dict();

dict.add(kimchi);
profile
possibilities

0개의 댓글