TypeScript에서 class를 공부하던 중 헷갈려서 정리하게 되었다. 둘 다 class 상속의 유형들이다.
implements: 인터페이스 구현
- 인터페이스에 정의된 구조를 강제할 때 사용함.
- 인터페이스는 실제 구현이 없고, 클래스가 인터페이스를 구현해야 함.
interface Flyable {
fly(): void;
}
class Bird implements Flyable }
fly() {
console.log("파닥파닥");
}
}
const myBird = new Bird();
myBird.fly(); // "파닥파닥"
- 인터페이스를 구현하는 클래스는 반드시 인터페이스의 모든 속성과 메서드를 정의해야 함.
- implements 절을 사용하면 클래스가 특정 인터페이스를 충족하는지 확인할 수 있음.
extends: 상속(Inheritance)
- 부모 클래스(기존 클래스)의 속성과 메서드를 상속받을 때 사용함.
- 자식 클래스는 부모 클래스의 모든 기능을 그대로 가져오고, 추가 기능을 정의하거나 오버라이딩 할 수 있음.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("다양한 소리");
}
}
class Cat extends Animal{
makeSound() {
console.log("야옹");
}
}
const myCat = new Cat("나비");
console.log(myCat.name); // "나비"
myCat.makeSound(); // "야옹"
'TypeScript' 카테고리의 다른 글
type과 interface (0) | 2025.02.13 |
---|