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;
}
}
이 외에도 오버라이딩 되는 메소드와 같은 타입을 반환해야 되는 것 같다.
//위 예시의 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)