타입 상속(Type Inheritance)은 TypeScript에서 클래스와 인터페이스 간에 타입을 상속하거나 확장하는 개념을 의미합니다. 이를 통해 기존에 정의된 클래스나 인터페이스의 멤버들을 새로운 클래스나 인터페이스에서 재사용하고 확장할 수 있습니다.
타입 상속은 코드의 재사용성과 구조화를 향상시키며, 객체지향 프로그래밍의 상속 개념과 유사한 개념입니다.
클래스 상속:
클래스 상속은 한 클래스가 다른 클래스의 멤버를 상속받아 기존 클래스를 확장하는 것을 의미합니다. 상속을 통해 기존 클래스의 속성과 메서드를 확장하거나 변경할 수 있습니다. 이를 통해 코드 재사용성을 높이고 관련된 클래스들을 구조화할 수 있습니다.
아래는 TypeScript에서 클래스 상속을 사용하는 예시입니다:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number) {
console.log(`${this.name} moves ${distance} meters.`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof! Woof!");
}
}
const dog = new Dog("Max");
dog.move(10); // 출력: Max moves 10 meters.
dog.bark(); // 출력: Woof! Woof!
위의 예제에서 Dog
클래스는 Animal
클래스를 상속받았습니다. Dog
클래스는 Animal
클래스의 name
속성과 move
메서드를 상속받아 사용하고, bark
메서드를 추가로 정의했습니다.
인터페이스 상속:
인터페이스 상속은 한 인터페이스가 다른 인터페이스의 멤버를 상속받는 것을 의미합니다. 상속을 통해 기존 인터페이스의 정의를 확장하거나 재사용할 수 있습니다.
아래는 TypeScript에서 인터페이스 상속을 사용하는 예시입니다:
interface Shape {
color: string;
getArea(): number;
}
interface Rectangle extends Shape {
width: number;
height: number;
}
class Square implements Rectangle {
color: string;
width: number;
height: number;
constructor(color: string, size: number) {
this.color = color;
this.width = size;
this.height = size;
}
getArea() {
return this.width * this.height;
}
}
const square = new Square("red", 5);
console.log(square.getArea()); // 출력: 25
위의 예제에서 Rectangle
인터페이스는 Shape
인터페이스를 상속받습니다. Square
클래스는 Rectangle
인터페이스를 구현하며, color
, width
, height
속성과 getArea
메서드를 구현합니다.
타입 상속은 TypeScript에서 코드를 구조화하고 재사용성을 높이는데 중요한 역할을 합니다. 상속을 통해 기존의 타입을 확장하고 변경함으로써 코드의 유연성과 확장성을 제공할 수 있습니다.