TS 클래스

HARIBO·2021년 12월 31일
0
  • public, protected, private 접근 한정자는 매개변수를 자동으로 this에 할당한다.
    • private: 해당 인스턴스 내에서만 접근 가능하다. 같은 클래스를 구현한 인스턴스 간에도 접근 가능하다.
    • protected: 해당 인스턴스, 인스턴스의 서브클래스에서 접근 가능하다.
type Name = 'apple' | 'grape';
type Color = 'red' | 'purple' | 'yellow';
type Num = number;

class Fruit {
  constructor(private name: Name, protected color: Color){}

  getName(){
    return this.name;
  }

  getColor(){
    return this.color;
  }
}

상속

super

  • 자식 클래스에서 부모 클래스의 메소드에 접근할 때 사용
  • 자식 클래스가 생성자를 사용하면 super()을 호출해야 부모 클래스에 접근 가능하다.

오버라이딩 조건

  1. 오버라이딩 되는 메소드의 매개변수 타입은 오버라이딩 메소드의 타입과 같거나 슈퍼타입 이어야 한다.
  2. 1.의 조건을 만족하면서, 오버라이딩 되는 메소드의 매개변수 개수가 오버라이딩 메소드의 매개변수 개수보다 많거나 같아야 한다.

이 외에도 오버라이딩 되는 메소드와 같은 타입을 반환해야 되는 것 같다.

//위 예시의 Fruit 클래스를 상속받는다.
class ChildrenFruit extends Fruit {
  public grape: Name;
  constructor(name: Name, color: Color, private number: Num){
    super(name, color);
    this.grape = 'grape';
  }
	
  //오버라이딩
  getName(){
    //name프로퍼티를 반환하는 부모 클래스의 메소드
    console.log(super.getName())

    //부모 클래스와 같이 Name타입을 반환하지만, grape프로퍼티를 반환한다.
    return this.grape;
  }

}

const a = new ChildrenFruit('apple', 'red', 5);
console.log(a.getName());  
//apple
//grape 

출처
보리스 체르니, 타입스크립트 프로그래밍(2021)

0개의 댓글